Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for empty string in C++ alternatives [closed]

Tags:

c++

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).

like image 995
fgalan Avatar asked Jan 02 '17 11:01

fgalan


People also ask

How do you check a string is empty or not in C?

To check if a given string is empty or not, we can use the strlen() function in C. The strlen() function takes the string as an argument and returns the total number of characters in a given string, so if that function returns 0 then the given string is empty else it is not empty.

How do I check if a string is empty or null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

Does empty string evaluate to false in C?

Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.

Is null and empty string the same in C?

They are different. A NULL string does not have any value it is an empty char array, that has not been assigned any value. An empty string has one element , the null character, '\0'. That's still a character, and the string has a length of zero, but it's not the same as a null string, which has no characters at all.


1 Answers

You can also use empty

if(s.empty())  
like image 158
artm Avatar answered Oct 11 '22 10:10

artm