C++ <string> - clear() Function
The C++ string::clear function is used to clear all characters of the string. This function makes the string empty with a length of 0 characters.
Syntax
void clear();
void clear() noexcept;
Parameters
No parameter is required.
Return Value
None.
Time Complexity
Constant i.e, Θ(1)
Example:
In the example below, the string::clear function is used to clear all characters of the string called str.
#include <iostream> #include <string> using namespace std; int main (){ string str = "Hello World!."; cout<<"Before clear() function: \n"; cout<<"str contains: "<<str<<"\n"; cout<<"str size: "<<str.size()<<"\n\n"; str.clear(); cout<<"After clear() function: \n"; cout<<"str contains: "<<str<<"\n"; cout<<"str size: "<<str.size(); return 0; }
The output of the above code will be:
Before clear() function: str contains: Hello World!. str size: 13 After clear() function: str contains: str size: 0
❮ C++ <string> Library