Compare two strings in C++
This post will discuss how to compare two strings in C++.
1. Using string::compare
The string::compare function compares the value of a string with the specified sequence of characters. The specified sequence can be another string or a pointer to a character array. It returns an integer value indicating the relationship between the two strings.
A zero status code indicates the strings are equal. A nonzero status code can be further positive or negative, indicating the compared string is longer or shorter than the specified string, respectively. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <string> int main() { std::string s1 = "Hello"; std::string s2 = "Hello"; int val = s1.compare(s2); if (val == 0) { std::cout << "Both strings are equal" << std::endl; } else if (val < 0) { std::cout << "First string is less than the second string" << std::endl; } else if (val > 0) { std::cout << "First string is greater than the second string" << std::endl; } return 0; } |
Output:
Both strings are equal
2. Using operator==
A simple solution to determine whether two strings are equal or not is using the == relational operator, which uses the string::compare for the comparison. Following is a simple example demonstrating its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> int main() { std::string s1 = "Hello"; std::string s2 = "Hello"; bool isEqual = s1 == s2; if (isEqual) { std::cout << "Both strings are equal" << std::endl; } else { std::cout << "Both strings are not equal" << std::endl; } return 0; } |
Output:
Both strings are equal
That’s all about comparing two strings in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)