In this C++ tutorial, you will learn how to check if a given string is empty or not, with example programs.
Check if string is empty in C++
To check if a given string is empty or not in C++, you can use string empty() method or directly compare the given string to an empty string.
1. Check if string is empty using string empty() method in C++
In the following program, we will check if given string in str
is empty or not using string empty() method.
Steps
- Given an input string in
str
. - Use the
empty()
method of thestring
class to check if the stringstr
is empty. - If the string is empty,
str.empty()
will evaluate to true, indicating that the string contains no characters. Else the string is not empty. We can use a C++ if else statement for this step withstr.empty()
as condition. - Inside the if-block, print a message to output that the string is empty.
- Inside the else-block, print a message to output that the string is not empty.
Program
main.cpp
</>
Copy
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "";
if (str.empty()) {
cout << "The string is empty." << endl;
} else {
cout << "The string is not empty." << endl;
}
return 0;
}
Output
The string is empty.
Now, let us take a non-empty string in str
, say “Hello World” and run the program.
main.cpp
</>
Copy
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
if (str.empty()) {
cout << "The string is empty." << endl;
} else {
cout << "The string is not empty." << endl;
}
return 0;
}
Output
The string is not empty.
2. Check if string is empty using string comparison in C++
In the following program, we will check if given string in str
is empty or not using string comparison.
Steps
- Given an input string in
str
. - Use the C++ Equal to operator
==
and pass the stringstr
as left operand and the empty string""
as right operand. - If the string is empty,
str == ""
will evaluate to true, indicating that the string contains no characters. Else the string is not empty. We can use a C++ if else statement for this step withstr == ""
as condition. - Inside the if-block, print a message to output that the string is empty.
- Inside the else-block, print a message to output that the string is not empty.
Program
main.cpp
</>
Copy
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "";
if (str == "") {
cout << "The string is empty." << endl;
} else {
cout << "The string is not empty." << endl;
}
return 0;
}
Output
The string is empty.
Conclusion
In this C++ Tutorial, we learned how to check if a given string is empty using string empty() method or string comparison, with examples.