Use of clear() and empty() methods of string class object
Learn to use methods <string object>.clear() andΒ <string object>.empty()
Learning Objectives
- Learning methods clear() and empty() of string class.
Source Code
|
|
Run Output
Code Understanding
string s;Β s=”C++ string”;
string object s declared and then assigned with a string literal. This can also be done in one statement if desired.
s.clear();
The clear method clears the whole string object s and empties it.
cout<<“Nothing will print after : if the string is cleared:”<<s<<endl;
If s object is emoty then obviously nothing will be printed in place of s.
if(s.empty()) cout<<“Successfully emptied”<<endl;
To verify emptiness <obj>.empty() method is used.
Notes
- In case of null terminated strings the clearing of string can still mean putting or null character at index 0. In case of clear() for string objects even the null character may not be there.
Common Errors
- Students sometime forget to but braces after clear and empty method. They are essential.
Suggested Filename(s): strcl-clear-empty.cpp
Created: 25-Jan-2018 23:57 | Updated: 26-Jan-2018 13:11|
