How to Check if String is Empty in C++
In C++, you can check if a string is empty by using the
empty() method, which returns true if the string has no characters. Alternatively, you can check if length() or size() returns zero to determine if the string is empty.Syntax
To check if a string is empty in C++, use the empty() method or compare the length() or size() to zero.
str.empty(): Returnstrueifstrhas no characters.str.length() == 0: Checks if the string length is zero.str.size() == 0: Equivalent tolength(), checks if string is empty.
cpp
bool isEmpty = str.empty(); // or bool isEmpty = (str.length() == 0); // or bool isEmpty = (str.size() == 0);
Example
This example shows how to check if a string is empty using empty() and length(). It prints messages based on whether the string has content or not.
cpp
#include <iostream> #include <string> int main() { std::string str1 = ""; std::string str2 = "Hello"; if (str1.empty()) { std::cout << "str1 is empty." << std::endl; } else { std::cout << "str1 is not empty." << std::endl; } if (str2.length() == 0) { std::cout << "str2 is empty." << std::endl; } else { std::cout << "str2 is not empty." << std::endl; } return 0; }
Output
str1 is empty.
str2 is not empty.
Common Pitfalls
Some common mistakes when checking if a string is empty include:
- Comparing the string directly to an empty string literal using
== ""works but is less efficient thanempty(). - Using
str == NULLis incorrect becausestd::stringis not a pointer. - Checking only the first character like
str[0] == '\0'can cause errors if the string is empty.
cpp
#include <iostream> #include <string> int main() { std::string str = ""; // Wrong: comparing to NULL (compilation error) // if (str == NULL) { } // Less efficient but works: if (str == "") { std::cout << "String is empty (using == \"\")." << std::endl; } // Correct and efficient: if (str.empty()) { std::cout << "String is empty (using empty())." << std::endl; } return 0; }
Output
String is empty (using == "").
String is empty (using empty()).
Quick Reference
| Method | Description | Returns |
|---|---|---|
| empty() | Checks if string has no characters | true if empty, false otherwise |
| length() == 0 | Checks if string length is zero | true if empty, false otherwise |
| size() == 0 | Same as length(), checks if string is empty | true if empty, false otherwise |
| == "" | Compares string to empty string literal | true if empty, false otherwise (less efficient) |
Key Takeaways
Use
empty() method to check if a string is empty efficiently and clearly.Checking
length() or size() equal to zero also works to detect empty strings.Avoid comparing
std::string to NULL or checking characters directly.Comparing to an empty string literal
"" works but is less efficient than empty().Always use standard string methods for safe and readable code.