empty()
is a member function of the basic_string
class template in the standard template library. It returns a bool that indicates whether or not a string is empty, i.e., it returns true if the string has zero characters in it.
your_string_variable.empty();
The following code demonstrates how the empty()
member function can be used. The first string contains a phrase and the second string contains a
The if-else statements can be used to check if a specific string is empty and print a message accordingly.
#include <iostream> int main() { std::string my_string1 = "Happy Learning at Educative!"; std::string my_string2 = " "; //contains a space std::string my_string3 = ""; std::cout<<"is my_string1 empty? "<<my_string1.empty()<<"\n"; std::cout<<"is my_string2 empty? "<<my_string2.empty()<<"\n"; std::cout<<"is my_string3 empty? "<<my_string3.empty()<<"\n"; if(my_string1.empty()) { std::cout<<"my_string1 is empty! "<<"\n"; } else { std::cout<<"my_string1 is not empty! "<<"\n"; } }
RELATED TAGS
CONTRIBUTOR
View all Courses