We first calculate the size of both strings and if the size of both strings is not equal then the program prints the message "Both strings are not equal" if the size of both stings is equal then the program compares Two Strings character by character and return if both strings are equal or not according to the string analysis.
Below is both method for comparing a string using library function or without using library functions. compare two strings without using the strcmp code below.
Using the Strcmp Library Function
strcmp(string1 ,string2)
Compare Two Strings Without Using Strcmp Function
This condition is used when the size of two strings is equal and we have to compare both string character by character.
Sponsor: Install and access your important work applications and software no matter where you are from any device ( PC / Android / iOS ) with a cloud desktop from www.CloudDesktopOnline.com. For cloud-related business software such as SharePoint, and Office365, try Apps4Rent.
Using the Strcmp Library Function
strcmp(string1 ,string2)
Compare Two Strings Without Using Strcmp Function
for (i = 0, j = 0; str1[i] != '\0', str2[j] != '\0'; i++, j++)
{
if (str1[i] == str2[j])
{
flag = 1;
}
else
{
flag = 0;
}
}
This condition is used when the size of two strings is equal and we have to compare both string character by character.
Sponsor: Install and access your important work applications and software no matter where you are from any device ( PC / Android / iOS ) with a cloud desktop from www.CloudDesktopOnline.com. For cloud-related business software such as SharePoint, and Office365, try Apps4Rent.
Read: C Program to Compare Two Strings Using Pointers
C Program to Compare Two Strings Without Using Strcmp
#include <bits/stdc++.h>
using namespace std;
int main()
{
/*C Program to Compare Two Strings Without Using Strcmp*/
cout << "=====================================";
cout << "\nVisit - www.programmingwithbasics.com";
cout << "\n=====================================";
char str1[20], str2[20], i = 0, j = 0, flag = 0;
cout << "\n\nEnter First String : \n";
gets(str1);
cout << "Enter Second String : \n";
gets(str2);
while (str1[i] != '\0')
{
i++;
}
while (str2[j] != '\0')
{
j++;
}
if (i != j)
{
flag = 0;
}
else
{
for (i = 0, j = 0; str1[i] != '\0', str2[j] != '\0'; i++, j++)
{
if (str1[i] == str2[j])
{
flag = 1;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
{
cout << "Both Strings Are Not Equal\n";
}
else
{
cout << "Both Strings Are Equal\n";
}
return 0;
}
for(i=0,j=0;str1[i]!='\0',str2[j]!='\0';i++,j++)
ReplyDelete{
if(str1[i]==str2[j])
flag=1;
else
flag=0 //There should be a else part...otherwise it fails to compare between hello &
//helli
}
Thank you Very Much Nick Moni for notifying Errors. Now Program Is Updated
DeleteKeep Sharing and Keep visiting
For instance :
ReplyDeleteAbcde
abcde
-> 1 ( following your code )
In fact, it was 0.