String Comparison
In C++, comparing strings is done using the ==
operator. This operator compares the content of the two strings and returns true
if they are equal, and false
otherwise.
Here's an example:
TEXT/X-C++SRC
1std::string str1 = "Hello";
2std::string str2 = "World";
3
4if (str1 == str2) {
5 std::cout << "The strings are equal." << std::endl;
6} else {
7 std::cout << "The strings are not equal." << std::endl;
8}
This code will output:
SNIPPET
1The strings are not equal.
It's important to note that string comparison is case-sensitive. So, for example, "hello" and "Hello" will be considered different strings.
In addition to the ==
operator, you can also use other comparison operators such as !=
, <
, >
, <=
, and >=
to compare strings based on their lexicographical order. These operators compare the strings character by character, starting from the first character.
TEXT/X-C++SRC
1std::string str1 = "Hello";
2std::string str2 = "World";
3
4if (str1 < str2) {
5 std::cout << "str1 is less than str2." << std::endl;
6} else {
7 std::cout << "str1 is greater than or equal to str2." << std::endl;
8}
xxxxxxxxxx
15
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
if (str1 == str2) {
std::cout << "The strings are equal." << std::endl;
} else {
std::cout << "The strings are not equal." << std::endl;
}
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment