Skip to main content

ft_strcmp — Compare Two Strings

Allowed functions: none

Reproduce the behavior of the function strcmp (man strcmp).

int ft_strcmp(char *s1, char *s2);

Solution

Download ft_strcmp.c
int ft_strcmp(char *s1, char *s2) {
while (*s1 && *s1 == *s2) {

s1++;
s2++;
}
return (*(unsigned char *)s1 - *(unsigned char *)s2);
}

How It Works

Goal: Compare two strings character by character and return their difference.

Approach: Walk both strings simultaneously while characters match, then return the difference at the point of divergence.

Step by step:

  1. Loop while *s1 is not the null terminator and *s1 == *s2 (characters still match).
  2. Advance both pointers each iteration.
  3. When the loop ends (mismatch or end of string), return the difference between the two current characters cast to unsigned char.

Key concept: Casting to unsigned char before subtracting ensures correct comparison for characters with values above 127, matching the behavior of the standard strcmp.