C String Functions
String functions are ready-made tools for work with strings. Strings showed how text is stored; these four tools count, copy, join, and compare it.
Count the letters
Word holds Hello, five letters before the end mark. strlen gives 5, and the print line shows 5.
#include <stdio.h>
#include <string.h>
int main() {
char word[10] = "Hello";
int len = (int)strlen(word);
printf("%d\n", len);
return 0;
}Copy a word
Hello is copied into copy, and strlen counts its five letters. The print lines show 5, then 72 for H.
#include <stdio.h>
#include <string.h>
int main() {
char copy[10] = {0};
strcpy(copy, "Hello");
int len = (int)strlen(copy);
printf("%d\n", len);
printf("%d\n", copy[0]);
return 0;
}Add words together
Greeting starts as Hello and grows by four characters to Hello Ada. strlen gives 9, and the print line shows 9.
#include <stdio.h>
#include <string.h>
int main() {
char greeting[20] = "Hello";
strcat(greeting, " Ada");
printf("%d\n", (int)strlen(greeting));
return 0;
}Example
#include <stdio.h>
#include <string.h>
int main() {
char first[10] = "Apple";
char second[10] = "Banana";
if (strcmp(first, second) == 0) {
printf("Same\n");
} else {
printf("Different\n");
}
return 0;
}Key points
- Add #include <string.h> at the top, next to #include <stdio.h>.
- strlen(word) gives how many letters word holds, not counting the end mark.
- strcpy(copy, "Hello"); writes Hello into copy.
- The row that takes the copy must have room for the text and the end mark.
- strcat(greeting, " Ada"); adds Ada to the end of greeting.
- The row that takes the longer text must have room for the extra letters.
- strcmp(a, b) gives 0 when the two words match.
First holds Apple and second holds Banana. strcmp gives a value other than 0, because the words do not match, so the print line shows Different.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which tool copies one string into another row?