String Comparison – compare() or == Operator
Just like the concatenation, we can do the string comparison using two methods:
1. == Operator
The equality operator can be used to compare the two strings as it is overloaded for this operation in the std::string class.
Syntax
string_object1 == string_object2
This will return true if both the strings are equal, otherwise returns false.
Example
std::string str1 = "apple"; std::string str2 = "banana"; if (str1 == str2) { std::cout << "Strings are equal"; } else { std::cout << "Strings are not equal"; }
Here, “Strings are not equal” will be printed as the == operator will return false.
2. compare()
The compare() function is a member function of std::string class which can be used to compare two strings.
Syntax
str1.compare(str2);
Parameters
- str2: It is the string to be compared. It can be both C or C++ style string.
Return Value
- If the strings are equal, return zero.
- If str1 is greater than str2, return value >0
- If str2 is greater than str1, return value <0
Example
string str1 = "Geeks"; string str2: = "Geeksfor"; int result = str1.compare(str2);
The result will contain a value less than zero as str2 is greater than str1.
We can also compare the substring of str2 using the compare function():
str1.compare(position, length, str2);
where,
- position: position of the first character substring.
- length: length of the substring.
- str2: String object to be compared.
String Functions In C++
A string is referred to as an array of characters. In C++, a stream/sequence of characters is stored in a char array. C++ includes the std::string class that is used to represent strings. It is one of the most fundamental datatypes in C++ and it comes with a huge set of inbuilt functions. In this article, will look at the functions of string computations.
Contact Us