Prime
Prime

Reputation: 4241

How do you check whether two strings are equal?

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?

Upvotes: 1

Views: 5729

Answers (1)

James McNellis
James McNellis

Reputation: 355069

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.

Upvotes: 15

Related Questions