C++ Compare Strings
Foreword
In this tutorial we will learn a safe way to compare std::string objects to each other.
Why not just with the == operator?
Depending on the string class implementation, it happens very often that the == operator does not do what we expect it to do. What often happens is that it just checks if the compared objects are equal, and not if the contained text is equal.
Example:
std::string s1 = "Something";
std::string s2 = "Something";
The text is equal, yet they are two different objects.
A compare like
if (s1 == s2)
Might return false here, because even though they contain the same text, the objects itself are different (we created two of them, both are different).
Now after reading the std::string documentation, it seems like we found the solution: string.compare(). What about this:
std::string s0 = "a";
std::string s1 = "a";
if (s0.compare(s1) == true))
{
// they are equal ?
}
This will fail because the compare function doesn't return true or false, but a number. A correct way to do it would be something like this:
std::string s0 = "a";
std::string s1 = "a";
if (s0.compare(s1) == 0))
{
// they are equal....
}
Now that works, but it's not that elegant. If we work on a big game and forget the "==0" then we will have a new bug every time, and we don't want that to happen.
Another problem is that depending on the IDE that we use, the string.compare() function might not be available if our IDE is using an older version of the C++ Standard Library.
Let's keep it as simple as possible and create a String Compare function for our library that works everywhere and that does exactly what we want it to do.
The Implementation
bool strcmp(std::string& s0, std::string& s1)
{
// compares two strings
//
if (s0.size() == s1.size())
{
for (unsigned int i = 0; i < s0.size(); ++i)
{
if (s0.at(i) != s1.at(i))
{
return false;
}
}
return true;
}
return false;
}
At first we take care of the obvious case where the strings have different lengths. If that happens, they can't be equal at all. Then we just compare each character of the two strings with each other, and that's it.
Example
std::string s0 = "a";
std::string s1 = "a";
if (strcmp(s0, s1)))
{
// they are equal....
}
if (!strcmp("test", "abc")))
{
// they are not equal....
}
Summary
The algorithm is almost trivial. It's very simple and it works, ready to be used in games.