How to use strcmp in C

How to use and Implement own strcmp in C

The strcmp function compares the string pointed to by s1 to the string pointed to by s2. If two strings are the same then strcmp() returns 0, otherwise, it returns a non-zero value.

Syntax strcmp in C:

int strcmp(const char *s1, const char *s2);

Parameters:

s1— pointer to the string1.

s2— pointer to the string2

Return:

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

 

Sometimes peoples require to create their own strcmp function for their project. So here in the below section, I shall describe the way to create the strcmp() function or you can say that we will see the implementation of strcmp in C.

Let’s see an example code to understand the functionality of the strcmp in C. In this C code, we will compare two given string.

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

#define SIZE 50

int main()
{
    char str1[SIZE], str2[SIZE];

    printf("Enter first string: ");
    fgets(str1,SIZE,stdin);

    printf("Enter second string: ");
    fgets(str2,SIZE,stdin);

    int ret = strcmp(str1,str2);
    if (ret==0)
    {
        printf("Strings are equal");
    }
    else
    {
        printf("Strings are unequal");
    }

    return 0;
}

Output:

strcmp in C

 

Note: If possible, you should use strncmp() or memcmp().

 

Some important points related to strcmp in C:

1.) strcmp() compares the two strings character by character starting from the first character until the characters in both strings are equal or a null character is encountered.

2.) If the first character in both strings is equal, then this function will check the second character, if this is also equal then it will check the third and so on.

3.) We must not use relational operators with string. When a relational operator (>, <, >=, <=, ==, !=) is used with strings they behave in a slightly different way. Let’s see an example code,

char *s1 = "Hello";

char *s2 = "Aticleworld";

 

What happens when we compare the above strings with strcmp?

strcmp(s1,s2);

 

Yes, you are right it returns a value greater than zero. But when we use a relational operator with the string then the output will be different and it varies system to system.

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

int main()
{
    char *s1 = "Hello";
    char *s2 = "Aticleworld";

    printf("Address of string pointed by s1 = %u\n", s1);
    printf("Address of string pointed by s2 = %u\n\n", s2);

    printf("(s1 == s2) = %d\n", s1 == s2);
    printf("(s1 > s2) = %d\n", s1 > s2);
    printf("(s1 < s2) = %d\n", s1 < s2);

    return 0;
}

Output:

string with relational operator in C

 

4.) If both strings will equal strcmp() function return zero.

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

int main()
{
    char *s1 = "Aticleworld";
    char *s2 = "Aticleworld";

    int ret = strcmp(s1,s2);

    printf("ret = %d\n",ret);

    return 0;
}

Output:

ret = 0

 

5.) When the first not matching character in left-string (s1) has a greater ASCII value than the corresponding character in right-string(s2), then it returns a value greater than zero.

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

int main()
{
    char *s1 = "World";
    char *s2 = "Aticleworld";

    int ret = strcmp(s1,s2);

    printf("ret = %d\n",ret);

    return 0;
}

Output:

ret = 1

 

6.) When the first not matching character in left-string (s1) has a lesser ASCII value than the corresponding character in right-string(s2), then it returns a value less than zero.

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

int main()
{
    char *s1 = "Aticleworld";
    char *s2 = "World";

    int ret = strcmp(s1,s2);

    printf("ret = %d\n",ret);

    return 0;
}

Output:

ret = -1

Note: C standard only explains that the return value of strcmp will be zero or greater than or less than according to the strings S1 and S2. So it might be the value of “ret” in the above program could be different on a different system. I had compiled the above-mentioned code in a code block with the GCC compiler.

7.)  It is the programmer’s responsibility to pass the valid string for the comparison in the strcmp() function.

 

8.) You must include string.h header file before using the strcmp function in C.

 

Watch the below video to understand the working of strcmp function in C programming.

 

 

How to write your own strcmp() function?

Your compiler/standard library will likely have a very efficient and tailored implementation of the strcmp() function. So if not require avoid to create own version of the strcmp function.

Note: Below function only to understand the working of strcmp. There is a lot of scenarios that are not handled in this function. You can handle the scenario as your requirement and if possible then use the standard strcmp function (library function).

int my_strcmp(char *s1, char *s2)
{
    int charCompareStatus = 0;

    while( ( *s1 != '\0' && *s2 != '\0' ) && *s1 == *s2 )
    {
        s1++;
        s2++;
    }

    //compare the mismatching character
    charCompareStatus = (*s1 ==*s2)?0:(*s1 >*s2)?1:-1;

    return charCompareStatus;
}

How it works:

The my_strcmp() function takes two arguments for strings of type pointers to char and returns an integer value. In this function in a while loop, I am iterating each character of both strings. If the characters are mismatched or get null character for any string then we are terminating the loop.

while( ( *s1 != '\0' && *s2 != '\0' ) && *s1 == *s2 )
{
    s1++;
    s2++;
}

 

Now after terminating the loop we are comparing the ASCII value of last character (character for both strings at the time of loop termination) of both strings.

Using the ternary operator we will assign the appropriate value to the status variable. If the last character of both strings is greater than, equal to, or less than zero, accordingly we will assign 1, 0, or -1 to the status variable.

charCompareStatus = (*s1 ==*s2)?0:(*s1 >*s2)?1:-1;

 

Let’s write a small application to test our own created strcmp function,

#include<stdio.h>


int my_strcmp(char *s1, char *s2)
{
    int charCompareStatus = 0;

    while( ( *s1 != '\0' && *s2 != '\0' ) && *s1 == *s2 )
    {
        s1++;
        s2++;
    }
    //compare the mismatching character
    charCompareStatus = (*s1 ==*s2)?0:(*s1 >*s2)?1:-1;

    return charCompareStatus;
}



int main()
{
    int ret = 0;

    //If s1 and s2 equal
    ret = my_strcmp("abc","abc");
    printf("ret = %d\n",ret);

    //if first char of s1 is large to s2
    ret = my_strcmp("bca","abc");
    printf("ret = %d\n",ret);

    //if first char of s1 is small to s2
    ret = my_strcmp("abc","bca");
    printf("ret = %d\n",ret);

    return 0;
}

Output:

ret = 0.
ret = 1.
ret = -1.

 

Write strcmp() function in one line (tricky question):

With the help of recursion, you can write the strcmp function in one line.

Note: It is only a tricky question for learning don’t use such type of hack in the real application might create a serious issue for your application. Let’s see the code,

int my_strcmp(const char *s1, const char *s2)
{
    return ((*s1 == *s2) ? ((*s1=='\0' && *s2=='\0') ? (0) : (my_strcmp(s1+1,s2+1))) : (((*s1 - *s2)<0) ?(-1) : (1)));
}

 

Let’s create a small application to test the above-created strcmp function,

#include<stdio.h>

int my_strcmp(const char *s1, const char *s2)
{
    return ((*s1 == *s2) ? ((*s1=='\0' && *s2=='\0') ? (0) : (my_strcmp(s1+1,s2+1))) : (((*s1 - *s2)<0) ?(-1) : (1)));
}


int main()
{
    int ret = 0;

    //If s1 and s2 equal
    ret = my_strcmp("abc","abc");
    printf("ret = %d\n",ret);

    //if first char of s1 is large to s2
    ret = my_strcmp("bca","abc");
    printf("ret = %d\n",ret);

    //if first char of s1 is small to s2
    ret = my_strcmp("abc","bca");
    printf("ret = %d\n",ret);

    return 0;
}

Output:

ret = 0
ret = 1
ret = -1

 

Recommended Articles for you: