Checking for Empty String in C++ Alternatives [Closed]

Checking for Empty String in C++ Alternatives [Closed]

There are (at least :) two ways of checking if an string is empty in C++, in particular:

if (s.length() == 0) {
  // string is empty
}

and

if (s == "") {
  // string is empty
}

Which one is the best from a performance point of view? Maybe the library implementation is clever enough so there isn't any different between them (in which case other criteria should decide, i.e. readibility) but I tend to think that the first alternative (using length()) is better.

Any feedback on this, please? (Or even a 3rd method better than the ones I have proposed).

4

3 Answers

You can also use empty

if(s.empty()) 
5

You can use the following:

s.empty();
s.size() == 0;
!s.size();

I would use empty from string library

string.empty()
Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.