Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
c++
communitycreator

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

Naima Abrar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

c
c++
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring