72. Implement Custom strcmp function

#include <stdio.h>

int custom_strcmp(const char *a, const char *b) {
    int i = 0;
    while (a[i] != '\0' && b[i] != '\0') {
        if (a[i] != b[i]) {
            return a[i] - b[i];  // Return ASCII difference
        }
        i++;
    }
    return a[i] - b[i];  // One might be longer than the other
}

int main() {
    char a[101], b[101];
    fgets(a, sizeof(a), stdin);
    fgets(b, sizeof(b), stdin);

    // Remove newline
    int i = 0;
    while (a[i]) {
        if (a[i] == '\n') { a[i] = '\0'; break; }
        i++;
    }
    i = 0;
    while (b[i]) {
        if (b[i] == '\n') { b[i] = '\0'; break; }
        i++;
    }

    printf("%d", custom_strcmp(a, b));
    return 0;
}

What does strcmp() really do?

It walks through both strings character by character. If it finds a mismatch, it returns the difference of their ASCII values. If it finishes both strings and finds no mismatch, it returns 0.

Why it’s important in firmware?

  • Used for comparing commands ("READ" vs "SET")
  • Lexical comparisons matter in bootloaders, menu navigation, etc.
  • Often used where string.h is not available

Solution Logic

  • Loop through characters
  • If any character differs, return the difference
  • If strings end, compare the null terminator too ('\0' - 'x' = -x)
     
Loading...

Input

apple apple

Expected Output

0