string.h
Read · 1 of 4
The string toolbox
#include <string.h> gives you: strlen(s) the length (without the '\0'), strcpy(dst, src) copy, strcat(dst, src) append, and strcmp(a, b), which is 0 when equal, negative when a comes first in dictionary order, positive otherwise.
a == b on two strings compares their addresses, not their letters. Always use strcmp.
strcpy and strcat don't check sizes: the destination must be big enough, or they write past its end.
Read this lesson as text
strlen, strcpy, strcat and strcmp, and why == doesn't compare strings.
The string toolbox
#include <string.h> gives you: strlen(s) the length (without the '\0'), strcpy(dst, src) copy, strcat(dst, src) append, and strcmp(a, b), which is 0 when equal, negative when a comes first in dictionary order, positive otherwise.
a == b on two strings compares their addresses, not their letters. Always use strcmp.
strcpy and strcat don't check sizes: the destination must be big enough, or they write past its end.
Length and comparison
#include <stdio.h>
#include <string.h>
int main() {
char a[20] = "pen";
char b[20] = "pencil";
strcat(a, "s");
printf("%d %d\n", (int) strlen(a), strcmp(a, "pens") == 0);
printf("%d\n", strcmp(a, b) > 0);
return 0;
}What does this print?
- 4 1 1
- 3 0 0
- 4 1 0
Show the answer
4 1 1 a becomes "pens" (4 letters), equal to "pens". "pens" vs "pencil": they differ at the 4th letter, 's' > 'c', so a comes after b.
Exercise: Password check
This should print Welcome when the typed word is open123, otherwise Denied. It always says Denied. Fix the comparison.
Exercise: Longest word
Read n (1 to 50), then n words (each under 30 letters). Print the longest word; if there's a tie, the one that came first.