Comparing string in C – strcmp

1. Strcmp function in string.h

When compared 2 number of C, we have done some very simple math <, >, >=, <=, ==, !=, however to compare the string, then we can not use calculations that need to use the function strcmp in library string.h.

Strcmp function compares the string s1 and s2 chain and gives results:

  • 1 If s1 is greater than s2
  • 0 If s1 like s2
  • -1 If s1 is less than s2

Noted: in Linux, This function returns a negative value, positive, 0 (is the distance between 2 different characters respectively in s1, s2).

For example the following program:

#include <stdio.h>
#include <string.h>

int main()
{
    char s1[20];
    char s2[20];                

    do 
    {
        printf("Enter s1: ");
        gets(s1);
        printf("Enter s2: ");
        gets(s2);

        int x = strcmp(s1, s2);
        printf("x = %d", x);

        if(x < 0) printf(" => %s < %s", s1, s2);
        if(x > 0) printf(" => %s > %s", s1, s2);
        if(x == 0)printf(" => %s = %s", s1, s2);

        printf("\n\n");

    } while ( strcmp(s1, s2) != 0);

    return 0;
}

Result:

Enter s1: Hang
Enter s2: Ho
x = -1 => Hang < Ho

Enter s1: Hong
Enter s2: She
x = 1 => Hong> Hon

Enter s1: Hung
Enter s2: hung
x = -1 => Hung < hung

Enter s1: offices
Enter s2: offices
x = 0 => The = Interest

2. Principle compare

Principle compare 2 chain that turns browsers 2 each character 2 Chain. Comparison of the ASCII code 2 characters that, character code that is greater than the larger chains and stop comparing. If a string of characters ever to compare the string before it smaller.

s1 s2 Result Reason
Hang Ho Hang < Ho do a < the (97 < 111)
Hong She Hong> Hon all characters from s2 to compare
Hung hung Hung < hung do H < h (72 < 104)
offices offices Interest = Interest 2 identical sequence

Refer ASCII encoding