std::string::empty() in C++
Last Updated :
09 Apr, 2024
Improve
The std::string::empty()
function in C++ is a predefined member function of the std::string class template. This function is used to check if a string is empty, i.e., whether its length is 0 or not, and returns a boolean value true if the string is empty otherwise, it returns false.
Syntax of String empty()
stringObj.empty();
Here, stringObj is the name of the string object.
Parameters of std::string::empty()
The std::string::empty()
function does not take any parameters.
Return Value of string::empty()
The return value of the std::string::empty() tells us whether the string is empty or not.
- It returns
true
if the string length is 0, otherwise, - It returns false.
Example of std::string::empty() in C++
Input:
str1="GeeksforGeeks
str2=""
Output:
str1 is not empty
str2 is empty
The below example illustrates how we can use an empty() function to check if the given string is empty or not in C++.
// C++ code to demonstrate std::string::empty() to check for
// empty string
#include <iostream>
using namespace std;
int main()
{
// declaring two strings
string str1 = "GeeksforGeeks";
string str2 = "";
// checking if the given string is empty or not
if (str1.empty()) {
// string is found empty
cout << "str1 is empty" << endl;
}
else {
// string is not empty
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
Time Complexity: O(1)
Auxilliary Space: O(1)