This post will discuss how to determine if a string is empty in C++.

1. Using string::empty function

One way to determine if a string is empty in C++ is to use the empty() function from the std::string class. This function returns a boolean value that indicates whether the string has no characters in it or not. For example, if we want to check if a string is empty or not, we can do something like this:

Download  Run Code

Output:

String is empty

 
The empty() function only checks if the string has no characters in it or not. It does not check if the string has only whitespace characters in it or not. For example, the string " " is not considered empty by the empty() function, even though it has no visible characters in it.

2. Using string::size function

Another way to determine if a string is empty in C++ is to use the size() function from the string class. These methods return an integer value that indicates the number of bytes in the string. To use the size() function to determine if a string is empty, we need to compare the returned value with zero. For example:

Download  Run Code

Output:

String is empty

3. Using string::length function

The string::length function is an alias of the string::size function. It returns the length of the string in bytes. An empty string would have a length of 0. It can be used as follows:

Download  Run Code

Output:

String is empty

That’s all about determining if a string is empty in C++.