typestar

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

  1. Zero means equal; the sign gives the ordering.
  2. strncmp limits the comparison to a prefix.
  3. == on two char * compares addresses, not contents.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Comparing & searching, step 5 of 13 in Strings & text.

← Previous Next →