C program to compare two strings without using string function(strcmp)
This C program is to compare two strings without using string function(strcmp).For example, str1=”code” and str2=”code” then on comparing we find that the two strings are equal.
Logic
We first check if both their lengths are equal.If strings are not equal, we need not go further with computation, thus increasing the efficiency of the program.If they are equal then we compare each string character by character.
Dry Run of the program
Take input str1 and str2.Let us take str1=code and str2=code
flag is set to 1 i.e. flag=1;
len1=strlen(str1) hence len1=4
len2=strlen(str2) hence len2=4
if(len1==len2) i.e if(4==4) true
1st iteration for(i=0;i<len1;i++) i .e. for(i=0;0<4;i++)
if(str1[i]!=str2[i]) i.e if(str1[0]!=str2[0]) i.e if(c!=c) false
2nd iteration for(i=1;i<len1;i++) i .e. for(i=1;1<4;i++)
if(str1[i]!=str2[i]) i.e if(str1[1]!=str2[1]) i.e if(o!=o) false
3rd iteration for(i=2;i<len1;i++) i .e. for(i=2;2<4;i++)
if(str1[i]!=str2[i]) i.e if(str1[2]!=str2[2]) i.e if(d!=d) false
4th iteration for(i=3;i<len1;i++) i .e. for(i=3;3<4;i++)
if(str1[i]!=str2[i]) i.e if(str1[3]!=str2[3]) i.e if(e!=e) false
For loop ends here as i=4 which is not less than len1(4)
if(flag==1) true
Hence the two strings are equal.
Program
#include<stdio.h> #include<string.h> void main() { char str1[100],str2[100]; int i,flag=1,len1,len2; printf("Enter string str1\n"); gets(str1); printf("Enter string str2\n"); gets(str2); len1=strlen(str1); len2=strlen(str2); if(len1==len2) { for(i=0;i<len1;i++) { if(str1[i]!=str2[i]) { flag=0; break; } } } else { flag=0; } if(flag==1) { printf("The two string are EQUAL!!!\n"); printf("%s(str1) = %s(str2)",str1,str2); } else { printf("The two string are NOT EQUAL!!!\n"); printf("%s(str1) != %s(str2)",str1,str2); } }