4.4 Strings
A C string is usually a character array ending with '\0'.
c
char word[6] = "hello";The visible word has 5 characters, but one more slot is needed for the terminator '\0'.
Common string functions live in <string.h>:
strlen()counts characters, not including'\0'.
strcmp()compares two strings.
strcpy()copies a string.
strcat()concatenates strings.
When copying or concatenating, the destination array must have enough space. C will not grow it automatically.
To read a whole line into a string, use fgets(). It reads at most size - 1 characters and always adds a '\0' at the end, which makes it safer than scanf("%s"): it never writes past the buffer and it can read text that contains spaces.
c
#include <string.h>
char line[64];
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0'; // drop the trailing newlinefgets() keeps the newline the user typed, so a common step is to find it with strcspn() and replace it with '\0'.
Loading interactive lab...
Loading concept check...
Loading practice...