Simvik

Implement strcmp

Compare two strings byte by byte. An easy embedded C problem (Arrays and strings), run and graded in the browser.

easy · Arrays and strings · strings · libc

Compare strings a and b. Return 0 if they are equal, a negative value if a sorts before b, and a positive value if it sorts after.

Characters are compared as unsigned char, as the C standard requires.

Starter code

int my_strcmp(const char *a, const char *b) {
  // 0 when equal, negative when a < b, positive when a > b.
  return 0;
}

Example tests

Differ in the last character

int r = my_strcmp("abc", "abd");
printf("%d\n", (r > 0) - (r < 0));

Expected output:

-1

Equal strings

int r = my_strcmp("reset", "reset");
printf("%d\n", (r > 0) - (r < 0));

Expected output:

0

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems