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?
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.
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.
There is no functionality difference between string and std::string because they're the same type.
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.
Use empty()
:
std::string s; if (s.empty()) // nothing in s
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