C++ Standard Library C++ STL Library
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

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 MyString.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string MyString = "Hello World!.";

  cout<<"Before clear() function: \n";
  cout<<"MyString contains: "<<MyString<<"\n";
  cout<<"MyString size: "<<MyString.size()<<"\n\n";

  MyString.clear();

  cout<<"After clear() function: \n";
  cout<<"MyString contains: "<<MyString<<"\n";
  cout<<"MyString size: "<<MyString.size()<<"\n\n";
  return 0;
}

The output of the above code will be:

Before clear() function: 
MyString contains: Hello World!.
MyString size: 13

After clear() function: 
MyString contains: 
MyString size: 0

❮ C++ <string> Library

5