Checking if a string is empty in C++
In this tutorial, we are going to learn about how to check if a string is empty or not in C++.
Checking string is empty
To check if a string is empty or not, we can use the built-in empty()
function in C++.
The empty()
function returns 1
if string is empty or it returns 0
if string is not empty.
Here is an example:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string user = "";
if(user.empty()){
cout << "user string is empty";
}else{
cout << "user string is not empty ";
}
return 0;
}
Output:
"user string is empty"
Similarly, we can also use the length()
function to check if a given string is empty or not.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string user = "";
if(user.length() === 0){
cout << "user string is empty";
}else{
cout << "user string is not empty ";
}
return 0;
}
or we can use the size()
function.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string user = "";
if(user.size() === 0){
cout << "user string is empty";
}else{
cout << "user string is not empty ";
}
return 0;
}
Note: The
length()
orsize()
functions returns the total number of characters in a given string.