What is std::basic_string::clear in C/C++?

clear() is a member function of the basic_string class in the Standard Template Library. It takes no parameters and it returns a string with zero characters (i.e., an empty string) regardless of the content of the input string. This is equivalent to assigning an empty string to a variable.

Syntax

your_string_variable.clear();

Code

#include <iostream>
#include <string>
int main()
{
std::string my_string1 = "Happy Learning at Educative!";
std::cout<<"Contents of string BEFORE clearing: " << my_string1<<"\n";
my_string1.clear();
std::cout<<"Contents of string AFTER clearing: " << my_string1 <<"\n";
if(my_string1.empty())
std::cout<<"string is empty";
else
std::cout<<"string is not empty";
}

Explanation

The code above demonstrates how the clear() member function can be used. The first string contains a phrase and, using the clear() function, the string is emptied.

Upon printing the same string after applying the clear() function, an empty string is returned. The if-else statements check if a specific string is empty, and print a message accordingly.

Free Resources