Google Add

Search

Program to Compare two Strings without using Strcmp

Write a C, C++ program to compare two strings without using strcmp() or any in-built library functions.

In my previous post, i have discussed how to compare two strings using strcmp .

In this program we take two strings as input from user. And compare each character of the string.

Interview Question on Strings.

Program to Compare two Strings without using Strcmp


#include <stdio.h>

int compare(char str1[],char str2[]) {

   int i=0,flag=0;
   
   while(str1[i]!='\0' && str2[i]!='\0'){
    
        if(str1[i]!=str2[i]){
         flag =1;
         break;
        }
   }
   
   /* If input string is empty. */
   
   if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
         flag = 1;
    else
         flag = 0;

  return flag;
 
}

int main(void) {

    char str1[100],str2[100];
    
    int result;
    
    printf("Enter two strings for comparison\n");
    
    gets(str1);
    gets(str2);
    
    /* Compare both strings. */
    
    result = compare(str1,str2);
    
    if(result==0){
     
     printf("\n Both strings are same");
     
    } else {
     
     printf("\n Either both strings are empty or different");
    }
 return 0;
}



Output:

Enter two strings for comparison -

c program

c program

Both strings are same

No comments:

Post a Comment