Program to compare two strings are equal or not
Written by
What are equal strings?
Two strings are said to be equal when they are equal in length and contain exactly the same characters at the exact same index.
Example
“Studymite” and “Studymite” are equal strings but “studymite” and “Studymite” are unequal strings as the case of first character is different in both.
Algorithm and Explanation
- Input two strings from the user and store them in s1 and s2 respectively.
- First check if the length of both strings are equal, if yes proceed to step 3 else print they are unequal and end the program.
- Set a counter ctr to zero (this will be set to 1 when an unequal character is found).
- Run a for loop to compare each character of the two strings.
- Compare the current character of the strings, if they are unequal set ctr to 1 and break out of the for loop. Do this till the last character is compared
- Now check if ctr is zero(all characters are equal since ctr can be modified only when unequal characters are encountered), hence the given strings are equal and print they are equal.
- If ctr is not zero(i.e. ctr=1), then we must have encountered an unequal character, therefore, print the given strings are unequal.
Code:
#include <iostream>
#include<string> //for using string data type
#include<cstdio> //for using getline function to input string
using namespace std;
int main()
{ string s1,s2;
cout<<"Enter First string\n"; //inputting string1
getline(cin,s1);
cout<<"Enter Second string\n"; //inputting string 2
getline(cin,s2);
if(s1.length()!=s2.length()) //comparing the string length
cout<<"The given strings are unequal";
else
{ int ctr=0; //comparing each character of the two strings
for(int i=0;i<s1.length();++i)
{ if(s1[i]!=s2[i])
{ ctr=1;
break;
}
}
if(ctr==0) //printing the result
cout<<"The given Strings are equal\n";
else
cout<<"The given strings are unequal";
}
return 0;
}
Output:
Enter First string: Study Mite
Enter Second string: Study Mite
The given strings are equal.