C String Functions
The header string.h has ready-made functions for the jobs you do with strings all the time: measuring, copying, joining and comparing. ctype.h adds functions that test and change single characters.
strlen: the length
strlen counts the characters before the terminator. It is not the same as sizeof, which gives the size of the whole array.
#include <stdio.h>
#include <string.h>
int main(void) {
char name[20] = "Asha";
printf("strlen: %zu\n", strlen(name));
printf("sizeof: %zu\n", sizeof(name));
return 0;
}strlen: 4 sizeof: 20
strcpy and strcat: copy and join
strcpy(destination, source) copies a string; strcat(destination, source) adds one to the end of another. The destination must be big enough for the result and the terminator; neither function checks.
#include <stdio.h>
#include <string.h>
int main(void) {
char full[40];
strcpy(full, "Asha");
strcat(full, " ");
strcat(full, "Kumar");
printf("%s (%zu letters)\n", full, strlen(full));
return 0;
}Asha Kumar (10 letters)
The safer snprintf(buffer, sizeof(buffer), "%s %s", first, last) builds a string and never writes past the end of the buffer, which makes it a good habit for any string you build.
strcmp: compare
Strings cannot be compared with ==, which compares addresses, not text. strcmp(a, b) returns 0 when the strings are equal, a negative number when a comes first in alphabetical (ASCII) order, and a positive number when it comes later.
#include <stdio.h>
#include <string.h>
int main(void) {
char password[] = "secret";
if (strcmp(password, "secret") == 0) {
printf("Access granted\n");
}
printf("apple vs banana: %s\n", strcmp("apple", "banana") < 0 ? "apple first" : "banana first");
return 0;
}Access granted apple vs banana: apple first
strchr and strstr: search
strchr(s, 'c') finds the first 'c' in s, and strstr(s, "text") finds a piece of text. Both return a pointer to the place found, or NULL when it is not there.
ctype.h: single characters
isalpha, isdigit, isspace, isupper and islower test a character; toupper and tolower change its case.
#include <ctype.h>
#include <stdio.h>
int main(void) {
char text[] = "Room 42b";
int letters = 0, digits = 0;
for (int i = 0; text[i] != '\0'; i++) {
if (isalpha((unsigned char)text[i])) letters++;
if (isdigit((unsigned char)text[i])) digits++;
text[i] = (char)toupper((unsigned char)text[i]);
}
printf("%s: %d letters, %d digits\n", text, letters, digits);
return 0;
}ROOM 42B: 5 letters, 2 digits
The cast to unsigned char is a good habit: these functions expect a value from 0 to 255, and some characters are negative numbers when stored in a plain char.
Practice exercises
- Read a word and print whether it is a palindrome (the same backwards), ignoring capital letters.
- Join a first name and a last name with
snprintfand print the result and its length. - Count the words in a sentence by counting spaces that are followed by a letter.