In C++, use == to compare std::string values. The class has no equals() method, which belongs to Java and some other languages. For C-style strings, which are char arrays, == does not compare the text at all, so the right tool is std::strcmp().
Why C++ has no equals() method
In Java, == on two String objects checks whether they are the same object, not whether their text matches. That is why Java programmers call equals() to compare content. C++ works differently. The std::string class overloads ==, so comparing two strings compares their characters. Python’s == on strings also compares content.
Using == with std::string
#include <iostream>
#include <string>
int main() {
std::string language = "C++";
if (language == "C++") {
std::cout << "Match\n";
}
if (language != "Java") {
std::cout << "Not Java\n";
}
}
Output:
Match
Not Java
The == and != operators are among the c comparison operators. For std::string, they compare the characters, so letter case and spaces matter.
When == does not compare text
#include <cstring>
#include <iostream>
int main() {
char a[] = "C++";
char b[] = "C++";
std::cout << (a == b) << '\n'; // 0: two different arrays
std::cout << (std::strcmp(a, b) == 0) << '\n'; // 1: same text
}
Output:
0
1
Here a and b are two separate arrays, so they sit at different addresses. == returns false even though the text matches. std::strcmp() reads the characters of both arrays up to the terminator and compares them, which is what you want.
For what strcmp returns in more detail, see what does strcmp do in C?
Which to use
| Type | Test for a match |
|---|---|
| std::string | a == b |
C-style string (char array or char *) |
std::strcmp(a, b) == 0 |
| Java String (not C++) | a.equals(b) |
Common mistakes
- Using
=instead of==. A single equals sign assigns a value. It does not compare, so theiftest does not check what you meant. - Expecting
==to ignore case."Cat"and"cat"are different strings. For a case-insensitive check, convert both strings to lowercase first, as explained in how to compare two strings in c. - Using
==on two char arrays. This compares addresses, as shown above.
For std::string, use ==, because C++ has no equals() method to call. For C-style strings, use std::strcmp() and check for 0. If you are not sure which type you have, look at the declaration: std::string or char.