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).
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.
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.
Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.
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.
You can also use empty
if(s.empty())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With