Determine if a string is empty in C++
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string s = ""; if (s.empty()) { std::cout << "String is empty" << std::endl; } else { std::cout << "String is not empty" << std::endl; } return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string s = ""; if (s.size() == 0) { std::cout << "String is empty" << std::endl; } else { std::cout << "String is not empty" << std::endl; } return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string s = ""; if (s.length() == 0) { std::cout << "String is empty" << std::endl; } else { std::cout << "String is not empty" << std::endl; } return 0; } |
Output:
String is empty
That’s all about determining if a string is empty in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)