How to Check if a String is Empty in C++?
Last Updated :
01 Feb, 2024
In C++, strings are the sequence of characters that are stored as std::string class objects. In this article, we will learn how to check if a string is empty in C++
Example
Input: str1="Hello! Geek" ; str2=""
Output:
str1 is not empty
str2 is empty
Checking if the String is Empty in C++
To check for an empty string we can use the std::string::empty() function because what the empty function does is it checks for the length of a string and if the string is empty, it returns true, otherwise, it returns false.
C++ Program to Check for Empty String
The below example demonstrates the use of the empty function to check for empty string.
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "Hello! Geek" ;
string str2 = "" ;
if (str1.empty()) {
cout << "str1 is empty" << endl;
}
else {
cout << "str1 is not empty" << endl;
}
if (str2.empty()) {
cout << "str2 is empty" << endl;
}
else {
cout << "str2 is not empty" << endl;
}
return 0;
}
|
Output
str1 is not empty
str2 is empty
We can also use compare() and size() functions to check if string is empty.
Share your thoughts in the comments
Please Login to comment...