String Comparison in C

Level 4187 keystrokes

Uses strcmp to compare strings and check for equality in a loop.

C code

// Array of string pointers
1char *words[] = {"apple", "banana", "apple", "cherry"};
// Loop through each word
2for (int i = 0; i < 4; i++) {
// strcmp returns 0 when equal, otherwise a negative or positive value
3 int cmp = strcmp(words[i], "apple");
// == on char * would compare addresses, so cmp == 0 is the right check
4 printf("%s: %s\n", words[i], cmp == 0 ? "match" : "no match");
5}

Output

apple: match
banana: no match
apple: match
cherry: no match
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • "× 16
  • ,× 6
  • ;× 5
  • =× 5
  • (× 3
  • )× 3
  • [× 3
  • ]× 3
  • :× 2
  • {× 2

More C examples at level 4

← C typing practice