Strings in C
In C, strings are arrays of characters terminated by a null character '\0'. They are used to store and manipulate text.
1. Basic String Handling in C
Strings are handled as character arrays and can be manipulated using standard library functions.
2. Declaring and Initializing Strings
Strings can be declared as character arrays or character pointers.
- Example: char str1[10] = "Hello"; char *str2 = "World";
3. String Input and Output
You can read and print strings using scanf, gets (unsafe), and printf functions.
- Example: char str[20]; scanf("%s", str); printf("%s", str);
4. String Manipulation Functions
- 4.1 strlen(): Returns the length of a string. Example: int len = strlen("Hello"); // 5
- 4.2 strcat(): Concatenates two strings. Example: strcat(str1, str2);
- 4.3 strchr(): Finds the first occurrence of a character in a string. Example: char *p = strchr(str, 'l');
- 4.4 strcpy(): Copies one string to another. Example: strcpy(dest, src);
- 4.5 strcmp(): Compares two strings. Example: int res = strcmp(str1, str2);
Codecrown