
Strings in C
? Strings in C
In C, strings are arrays of characters terminated by a null character (\0
).
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};
? Declaring Strings
char name[10] = "Alice";
Or:
char name[] = {'A', 'l', 'i', 'c', 'e', '\0'};
? Reading Strings
char name[20];scanf("%s", name); // stops at whitespace
To read full lines (with spaces), use:
fgets(name, sizeof(name), stdin);
?? Printing Strings
printf("Name: %s\n", name);
? Common String Functions (from <string.h>
)
Function | Description |
---|---|
strlen(str) | Returns length of the string |
strcpy(dest, src) | Copies one string to another |
strcat(dest, src) | Concatenates strings |
strcmp(s1, s2) | Compares two strings |
strrev(str) | Reverses string (not standard C) |
strchr(str, ch) | Finds first occurrence of char |
strstr(s1, s2) | Finds substring |
? Example
#include #include <string.h>int main() { char str1[20] = "Hello"; char str2[] = "World"; strcat(str1, str2); // str1 becomes "HelloWorld" printf("Combined: %s\n", str1); printf("Length: %lu\n", strlen(str1)); return 0;}
?? Notes
Always ensure your strings are null-terminated.
Be careful with buffer overflows when using functions like
strcpy
.