Comparing strings in C
strcmp orders text and never returns a bool, so compare its result against zero.
#include <string.h>
int is_command(const char *arg, const char *name) {
return strcmp(arg, name) == 0;
}
int has_prefix(const char *text, const char *prefix) {
return strncmp(text, prefix, strlen(prefix)) == 0;
}
const char *smaller_of(const char *a, const char *b) {
return (strcmp(a, b) <= 0) ? a : b;
}
int addresses_differ(void) {
const char *a = "same";
char b[] = "same";
return (a != b) && (strcmp(a, b) == 0);
}
How it works
- Zero means equal; the sign gives the ordering.
strncmplimits the comparison to a prefix.==on twochar *compares addresses, not contents.
Keywords and builtins used here
addresses_differcharconsthas_prefixintis_commandreturnsmaller_ofvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 423
- Tokens
- 140
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 84 seconds.
Step 1 of 3 in Comparing & searching, step 5 of 13 in Strings & text.