The std::string::clear() function is a member of the std::string class defined in the <string> header. It removes the contents of a string without destroying the string object itself.
- Makes the string empty by removing all stored characters.
- Commonly used before storing new data in the same string object.
#include <iostream>
#include <string>
using namespace std;
// Function to demo clear()
void clearDemo(string str)
{
// Deletes all characters in string
str.clear();
cout << "After clear : ";
cout << str;
}
// Driver code
int main()
{
string str("Hello World!");
cout << "Before clear : ";
cout << str << endl;
clearDemo(str);
return 0;
}
Output
Before clear : Hello World! After clear :
Explanation: The clear() function removes every character from the string, leaving it empty.
Syntax
string_name.clear();
string_name is the string whose contents are to be removed.
Additional Examples
The following examples demonstrate different uses of std::string::clear().
1. Clearing a String Before Reusing It
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Programming";
str.clear();
str += "GeeksforGeeks";
cout << str;
return 0;
}
Output
GeeksforGeeks
Explanation: The original contents are removed using clear(), and the same string object is reused to store new text.
2. Checking Whether a String Becomes Empty
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
str.clear();
if (str.empty())
cout << "String is empty";
return 0;
}
Output
String is empty
Explanation: After calling clear(), the empty() function confirms that the string contains no characters.
Applications
std::string::clear() is commonly used in the following situations:
- Resetting a string before storing new data.
- Reusing the same string object multiple times.
- Clearing temporary string buffers.
- Removing all contents without creating another string.
Best Practices
Follow these practices while using std::string::clear():
- Use clear() when the entire string needs to be emptied.
- Prefer reusing an existing string instead of creating a new one repeatedly.
- Use empty() to verify whether the string contains any characters after clearing.
- Use erase() instead when only a portion of the string needs to be removed.