If I have two pieces of character data, what is the best way to compare them (test for equality with ==
)?
That is, which type is best for this comparison; a const char*
, a std::string
?
If your goal is simply to compare strings for equality then it doesn't really matter whether you use null-terminated strings or some string container like std::string
.
You can use std::strcmp
to compare two null-terminated strings just as easily as you can use operator==
to compare two std::string
objects. The overloaded operator does make code cleaner and easier to read in most cases.
Of course, since you're programming in C++, you should be using std::string
or some other string container and not manipulating raw null-terminated data, wherever possible.