1. String class clear/ Erase /pop_back
1.1 STD: : string: : clear
prototype: void clear() noexcept; description: clears the contents of the string to make the source string an empty string (0 characters in length). Code examples:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str;
cout<<"Please enter one line, ending with a newline character."<<endl;
getline(std::cin, str);
cout<<"Before Clearance.str = \""<<str<<"\", str.size = "<<str.size()<<endl;
str.clear();
cout<<"After emptying.str = \""<<str<<"\", str.size = "<<str.size()<<endl;
if(true == str.empty())
{
cout<<"The source string has been cleared."<<endl;
}
system("pause");
return 0;
}
=>Please enter one line, ending with a newline character.
hello world.
Before clearing: str = "hello world.", str.size = 12
Empty: str = "", str.size = 0
The source string has been cleared.
1.2 STD: : string: : erase
archetype: string& erase (size_t pos = 0, size_t len = npos); note: delete the len characters of the source string starting with the subscript pos, and return the modified string. stereotype: iterator erase (const_iterator p); description: deletes the character pointed to by iterator p in the source string, returning the position of the iterator after deletion. stereotype: iterator erase (const_iterator first, const_iterator last); note: delete all characters in the source string iterator range [first, last], returning the position of the iterator after deletion.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str("This is an example sentence.");
cout<<str<<endl;
str.erase(10, 8);
cout<<str<<endl;
str.erase(str.begin()+9);
cout<<str<<endl;
str.erase(str.begin()+5, str.end()-9);
cout<<str<<endl;
system("pause");
return 0;
}
=>This is an example sentence.
This is an sentence.
This is a sentence.
This sentence.
1.3 STD: : string: : pop_back
Void pop_back(); void pop_back(); : removes the last character of the source string, effectively reducing its length. Code examples:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str("hello world!");
str.pop_back();
cout<<str<<endl;
system("pause");
return 0;
}
=>hello world
[1] network resources:
http://www.cplusplus.com/reference/string/string/clear/
http://www.cplusplus.com/reference/string/string/erase/
http://www.cplusplus.com/reference/string/string/pop_back/