Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a std::string is set or not?

Tags:

c++

If using a char*, I can initialize it to NULL and later check if it is set by doing a comparison. How to do the same thing for a std::string? How to check if the string is set or not?

EDIT: What if the string I set to is also empty? Do I have to use an additional flag to check if the std::string is set or not?

like image 988
nakiya Avatar asked Oct 11 '10 04:10

nakiya


People also ask

How do I check if a std::string is Nullptr?

You can't; at least not the same way you can test whether a pointer is NULL . A std::string object is always initialized and always contains a string; its contents by default are an empty string ( "" ). You can test for emptiness (using s. size() == 0 or s.

How check string is null or not in C++?

To check if a string is empty or not, we can use the built-in empty() function in C++. The empty() function returns 1 if string is empty or it returns 0 if string is not empty. Similarly, we can also use the length() function to check if a given string is empty or not. or we can use the size() function.

Is it string or std::string?

There is no functionality difference between string and std::string because they're the same type.

Is std::string empty?

std::string::emptyReturns whether the string is empty (i.e. whether its length is 0). This function does not modify the value of the string in any way.


1 Answers

Use empty():

std::string s;  if (s.empty())     // nothing in s 
like image 50
GManNickG Avatar answered Sep 20 '22 13:09

GManNickG