C Program to Compare Two Strings Using User Defined Function

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

C Source Code: String Compare User Defined Function


#include<stdio.h>

/* Function Protptype*/
int mystrcmp(char str1[40], char str2[40]);

/* Main Function */
int main()
{
 char str1[40], str2[40];
 int d;

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

 /* Function Call */
 d = mystrcmp(str1, str2);

 if(d==0)
 {
  printf("Given strings are same.");
 }
 else
 {
  printf("Given strings are different.");
 }

 return 0;
}

/* Function Definition */
int mystrcmp(char str1[40], char str2[40])
{
 int d,i, len1=0, len2=0, flag=0;
 /* 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)
 {
  return(1);
 }
 else
 {
  for(i=0;i< len1;i++)
  {
   if(str1[i]!=str2[i])
   {
    flag=1;
    break;
   }
  }
  
  if(flag==0)
  {
   return(0);
  }
  else
  {
   return(1);
  }
 }
}

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.