In C++ == and compare() both are used to compare strings and find if the given strings are equal or not but they differ in working. In this article, we will learn the key differences between == and compare() of string in C++.
"=="
Operator in C++
The == operator in C++ is used to compare two strings it is a boolean operator that returns true if the given strings are equal and returns false if they are not equal (in case each corresponding character of string or length does not match).
Syntax of “==” operator in C++
str1 == str2
Example of “==” Operator in C++
The below example demonstrates the use of the “==” operator to compare the strings.
// C++ program to demonstrate the use of == operator to // compare the strings #include <iostream> #include <string> using namespace std;
int main()
{ // defining strings to be compared
string s1 = "GfG" ;
string s2 = "GeeksforGeeks" ;
// comparing string using == operator
if (s1 == s2) {
cout << "Strings are Equal\n" ;
}
else {
cout << "Strings are not Equal\n" ;
}
return 0;
} |
Strings are not Equal
String compare() in C++
The std::string::compare() function is also used to compare strings but it returns an integer unlike == operator to tell how the string are related lexicographically.
- returnValue == 0: Strings are equal.
- returnValue <0: First string is lexicographically less than the second string.
- returnValue >0: First string is lexicographically greater than the second string.
Syntax of Compare()
int returnValue = str1.compare(str2)
Example of compare() in C++
The below example demonstrates the use compare() function to compare strings in C++.
// C++ program to demonstrate the use compare() function to // compare strings #include <iostream> #include <string> using namespace std;
int main()
{ string s1 = "GfG" ;
string s2 = "GeeksforGeeks" ;
int value = s1.compare(s2);
if (value == 0) {
cout << "The strings are Equal\n" ;
}
// value > 0 (s1 is greater than s2)
else if (value > 0) {
cout << "The string1 is greater than string 2\n" ;
}
// Now the only left value < 0 (s1 is smaller than s2)
else {
cout << "The string1 is smaller than string 2\n" ;
}
return 0;
} |
The string1 is greater than string 2
Difference Between C++ String == and Compare()
The below table illustrates the key difference between C++ string == and compare().
Feature |
== Operator |
compare() Method |
---|---|---|
Usage |
Check two strings have same content or not |
Compare two strings Lexicographically |
Syntax |
string1 == string2 |
string1.compare(string2) |
Return Type |
Boolean (true or false) |
Integer (positive,negative or ‘0’) |
Flexibility |
Limited to full string comparison |
Can compare whole strings, substrings, or parts of strings |
Use Case |
When we need to check if two strings are identical or not |
When we need Determines lexical ordering along with equality |