xxxxxxxxxx
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // string.h adds a lot of pre-defined functions
int main() {
// There are 2 ways to define a basic string in C:
char string1[] = "This is a string!";
// Notice that here, I use the brackets [] to tell C that this is a
// char array.
// I can also define a string this way:
char* string2 = "This is another string!";
// If I didn't want to ititialize the string yet:
char string3[10];
// This creates a string 10 bytes long, with no value initialized yet.
// Another way to do this is by using malloc/calloc:
char* string4 = malloc(10);
// However, with this method, I would have to free the string later,
// because it is stored on the heap:
free(string4);
}
xxxxxxxxxx
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_LENGTH 100
#define NUM_STRINGS 10
int main(){
char arr[NUM_STRINGS][MAX_LENGTH] = {""};
arr2[0] = "string literal"; // Not permitted
strcpy(arr[0], "hello world");
printf("%s\n", arr[0]);
printf("%s\n", strcpy(arr[0], "hello world"));
exit(EXIT_SUCCESS);
}
xxxxxxxxxx
// C program to illustrate strings
#include <stdio.h>
#include <string.h>
int main()
{
// declare and initialize string
char str[] = "Geeks";
// print string
printf("%s\n", str);
int length = 0;
length = strlen(str);
// displaying the length of string
printf("Length of string str is %d", length);
return 0;
}
xxxxxxxxxx
1. char str[] = "GeeksforGeeks";
2. char str[50] = "GeeksforGeeks";
3. char str[] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. char str[14] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
xxxxxxxxxx
Strings are defined as an array of characters. The difference between a
character array and a string is the string is terminated with a special
character ‘\0’.
xxxxxxxxxx
#include<stdio.h>
void main(){
int date;
char fn[50], ln[50];
printf("Enter your first name = ");
scanf("%s",&fn);
printf("Enter your last name = ");
scanf("%s",&ln);
printf("Enter your year of birth = ");
scanf("%d",&date);
printf("Your first name = %s\nlast name = %s\nand year of birth = %d", fn, ln, date);
}
xxxxxxxxxx
#include <stdio.h>
int main() {
char str[100]; // declaring a string of size 100
// Alternatively, you can declare a string and initialize it with a value:
// char str[] = "Hello, World!";
// Accessing and modifying the string:
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = '\0'; // Null-terminating the string
printf("String: %s\n", str);
return 0;
}
xxxxxxxxxx
#define LEN 10
// this converts to string
#define STR_(X) #X
// this makes sure the argument is expanded before converting to string
#define STR(X) STR_(X)
[ ]
scanf("Name: %" STR(LEN) "s", arr);