Become Our Fan on Social Sites!

Facebook Twitter

Google+ RSS YouTube

Friday 27 September 2013

C Program To Compare Two Strings

Following c programs checks two strings are same / equal or not. There are three versions of string comparison: 1) Using strcmp() function, 2) Without using strcmp() function and 3) Using pointer. Program using strcmp() function is not included in following codes.


1) Without using strcmp() library function



  #include<stdio.h>  
 int compare_string(char[],char[]);  
 int main()  
 {  
   char str1[100], str2[100];  
   int result;  
   printf("Enter String-1 : ");  
   gets(str1);  
   printf("Enter String-2 : ");  
   gets(str2);  
   result = compare_string(str1,str2);  
   if(result == 0)  
     printf("Strings are same");  
   else  
     printf("Strings are not same");  
   return 0;  
 }  
 int compare_string(char str1[], char str2[])  
 {  
   int index = 0;  
   while( str1[index] == str2[index] )  
   {  
     if( str1[index] == '\0' || str2[index] == '\0' )  
       break;  
     index++;  
   }  
   if( str1[index] == '\0' && str2[index] == '\0' )  
     return 0;  
   else  
     return 1;  
 }  

2) String comparison using pointer

  #include<stdio.h>  
 int compare_string(char*, char*);  
 int main()  
 {  
   char str1[100], str2[100], result;  
   printf("Enter String-1 : ");  
   gets(str1);  
   printf("Enter String-2 : ");  
   gets(str2);  
   result = compare_string(str1, str2);  
   if ( result == 0 )  
     printf("Strings are same");  
   else  
     printf("Strings are not same");  
   return 0;  
 }  
 int compare_string(char *str1, char *str2)  
 {  
   while( *str1 == *str2 )  
   {  
     if ( *str1 == '\0' || *str2 == '\0' )  
       break;  
     str1++;  
     str2++;  
   }  
   if( *str1 == '\0' && *str2 == '\0' )  
     return 0;  
   else  
     return 1;  
 }  

0 comments :

Post a Comment