Comparing String objects using Relational Operators in C++
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.
Relational operator return either true or false value, true if the corresponding comparison holds, false otherwise.
#include <iostream>
using namespace std;
void compreStrs(string s1, string s2)
{
string s3 = s1 + s2;
if (s1 != s2)
cout << s1 << " is not equal to " << s2 << endl;
if (s1 > s2)
cout << s1 << " is greater than " << s2 << endl;
else if (s1 < s2)
cout << s1 << " is smaller than " << s2 << endl;
if (s3 == s1 + s2)
cout << s3 << " is equal to " << s1 + s2 << endl;
}
int main()
{
string s1("geeks");
string s2("forgeeks");
compreStrs(s1, s2);
return 0;
}
Output
geeks is not equal to forgeeks geeks is greater than forgeeks geeksforgeeks is equal to geeksforgeeks
Important Conditions:
- s1 < s2 : A string s1 is smaller than s2 string, if either, length of s1 is shorter than s2 or first mismatched character is smaller.
- s1 > s2 : A string s1 is greater than s2 string, if either, length of s1 is longer than s2 or first mismatched character is larger.
- <= and >= have almost same implementation with additional feature of being equal as well.
- If after comparing lexicographically, both strings are found same, then they are said to be equal and equality is checked using ==