C String Functions
The <string.h> header provides many useful functions for working with strings, such as measuring length, copying, concatenating and comparing them.
Because C strings are just char arrays, these functions rely on the null terminator to know where a string ends, so they can behave unpredictably on strings without one.
#include <string.h>
strlen(s); strcpy(dest, src); strcat(dest, src); strcmp(s1, s2);Common functions
strlen() returns the length of a string (excluding the null terminator). strcpy() copies one string into another, and strcat() appends one string onto the end of another.
Comparing strings
strcmp() compares two strings lexicographically, returning 0 if they are equal, a negative number if the first is 'less than' the second, and positive otherwise.
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Hello";
printf("%lu\n", strlen(s));
return 0;
}5strlen counts the characters before the null terminator, not including it.
#include <stdio.h>
#include <string.h>
int main() {
char a[20] = "Hello, ";
char b[] = "World!";
strcat(a, b);
printf("%s\n", a);
return 0;
}Hello, World!strcat appends b onto the end of a, so a's buffer must be large enough.
Key points
- strlen() returns string length excluding the null terminator.
- strcpy() and strcat() require the destination buffer to be big enough.
- strcmp() returns 0 when two strings are equal.
- All these functions require #include <string.h>.
