C Program to Compare Two String Without strcmp

This C program compares two string without using string handling function strcmp().

C Source Code: String Comparison Without strcmp()


#include<stdio.h>

int main()
{
 char str1[40], str2[40];
 int d,i, len1=0, len2=0, flag=0;

 printf("Enter first string:\n");
 gets(str1);
 printf("Enter second string:\n");
 gets(str2);

 /* Finding length of first string */
 for(i=0;str1[i]!='\0';i++)
 {
  len1++;
 }

 /* Finding length of first string */
 for(i=0;str2[i]!='\0';i++)
 {
  len2++;
 }

 if(len1!=len2)
 {
  printf("Given strings are different.");
 }
 else
 {
  for(i=0;i< len1;i++)
  {
   if(str1[i]!=str2[i])
   {
	  flag=1;
    break;
   }
  }
  
  if(flag==0)
  {
   printf("Given strings are same.");
  }
  else
  {
   printf("Given strings are different.");
  }
 }

 return 0;
}

Output

Run 1
-------------
Enter first string:
Welcome to C ↲
Enter second String:
Welcome to C ↲
Given strings are same.

Run 2:
-------------
Enter first string:
Welcome ↲
Enter second String:
Welcome to C ↲
Given strings are different.

Note: ↲ represents ENTER key is pressed.