Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
string
empty
communitycreator

What is basic_string::empty in C/C++?

Naima Abrar

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.

Syntax

your_string_variable.empty();

Code explanation

The following code demonstrates how the empty() member function can be used. The first string contains a phrase and the second string contains a spaceconsidered as a character. Hence, the output shows 00 or False, indicating that the strings are NOT empty. In contrast, the third string is empty, which is confirmed by the output of 11 or True.

The if-else statements can be used to check if a specific string is empty and print a message accordingly.

Code

#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

c++
string
empty
communitycreator
RELATED COURSES

View all Courses

Keep Exploring