Learn C · lesson 30 of 60 · about 8 minutes
String Functions
Warn when root runs the report and make a label for the log: measure, copy, join and compare strings with the functions in string.h.
What you'll learn
- Measure with strlen
- Copy and join with strcpy and strcat
- Compare with strcmp
Who's running the report?
Running the report as root, the all-powerful admin account, deserves a warning. But user == "root" never matches, even when you type root: == compares where two strings are stored, not their letters. The functions in string.h do the jobs = and == can't, so the report can compare the name with strcmp, and build a label like ada@codiqo-box with strcpy and strcat.
The string.h toolkit
| Function | Does |
|---|---|
| strlen(s) | number of chars before '\0' |
| strcpy(dst, src) | copies src into dst |
| strcat(dst, src) | adds src to the end of dst |
| strcmp(a, b) | 0 if equal, negative or positive otherwise |
You can't use = to copy a string or == to compare two strings in C. These functions do it instead.
Working with strings
#include <stdio.h>
#include <string.h>
int main(void) {
char greeting[32];
strcpy(greeting, "Hello");
strcat(greeting, ", Phoebe");
printf("%s (%zu chars)\n", greeting, strlen(greeting));
char answer[] = "def";
if (strcmp(answer, "def") == 0) {
printf("Correct keyword\n");
}
return 0;
}Output
Hello, Phoebe (13 chars)
Correct keywordstrcmp gives 0 for a match
strcmp doesn't return true or false. It returns 0 when the strings are the same, a negative number when the first comes earlier in alphabetical (character code) order, and a positive one when it comes later. So the test for a match is always strcmp(a, b) == 0. It's case-sensitive: "Root" and "root" are different strings.
Matching a command
#include <stdio.h>
#include <string.h>
int main(void) {
char cmd[] = "status";
printf("%d\n", strcmp(cmd, "status") == 0);
printf("%d\n", strcmp(cmd, "Status") == 0);
printf("%d\n", strcmp("apple", "banana") < 0);
return 0;
}Output
1
0
1Tip
strcpy and strcat trust you completely: if the destination array is too small, they write past its end. Always make the destination big enough.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.