Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Comparing two strings

1) Using library function strcmp()

This function is used to compare two strings & check whether they are equal or not.

Syntax

int strcmp(const char *string1, const char string2);

Value returned by strcmp() at different conditions

Condition Value returned by strcmp() fun
If both the strings are equal Zero
If string1 is greater than string2 Positive integer
If string1 is less than string2 Negative integer

Example no 1
C Programming Language Comparing Two Same Strings using strcmp() Function
In this example, both the strings are exactly same therefore strcmp(string1,string2) returns zero.

Example no 2
C Programming Language Comparing Two Different Strings using strcmp() Function 1
In this example, first two characters J & o of string1 & string2 are same but third character H of string1 and h of string2 are different.
ASCII value of H (72) is less than ASCII value of h (104).
Therefore string1 is less than string2.
Therefore strcmp(string1,string2) returns negative integer.

Example no 3
C Programming Language Comparing two Different Strings using strcmp() Function 2
In this example, first three characters J, o & h of string1 & string2 are same but fourth character n of string1 & N of string2 are different.
ASCII value of n (110) is greater than ASCII value of N (78).
Therefore string1 is greater than string2.
Therefore strcmp(string1, string2) returns positive integer.

Example

#include<stdio.h>
#include<string.h>
int main()
{
    char string1[20];
    char string2[20];
    printf("\n Enter String 1 :: ");
    gets(string1);
    printf("\n Enter String 2 :: ");
    gets(string2);
    if((strcmp(string1,string2))==0)
    {
        printf("\n String1 and String2 are same");
    }
    else
    {
        printf("\n String1 and String2 are not same");
    }
    return 0;
}

Output

Enter String 1 :: C Programming

Enter String 2 :: C Programming

String1 and String2 are same

2) Without using a library function

Example

#include<stdio.h>
int main()
{
     int x=0,value=1;
     char string1[20];
     char string2[20];
     
     printf("\n Enter String 1 :: ");
     gets(string1);
     printf("\n Enter String 2 :: ");
     gets(string2);
     
     while(string1[x]==string2[x])
     {
         if(string1[x]=='\0')
         {
             value = 0;
         }
         x++;
     }

     if(value==0)
     {
         printf("\n String1 and String2 are same");
     }
     else
     {
         printf("\n String1 and String2 are not same");
     }
     return 0;
}

Output

Enter String 1 :: Very Good

Enter String 2 :: Very Good

String1 and String2 are same

 

Leave a reply