clear:清空字符串
#include <iostream> #include <string> using namespace std; int main () { string str; cout<<"请输入一行字符,以换行符结束:"<<endl; getline(std::cin, str); cout<<"清空前:str = ""<<str<<"", str.size = "<<str.size()<<endl; str.clear(); cout<<"清空后:str = ""<<str<<"", str.size = "<<str.size()<<endl; if(true == str.empty()) { cout<<"源字符串已被清空"<<endl; } system("pause"); return 0; } ;=>请输入一行字符,以换行符结束: ; hello world. ;清空前:str = "hello world.", str.size = 12 ;清空后:str = "", str.size = 0 ; 源字符串已被清空
std::string::erase
原型:string& erase (size_t pos = 0, size_t len = npos);
说明:删除源字符串以下标为pos开始的len个字符,返回修改后的字符串。
原型:iterator erase (const_iterator p);
说明:删除源字符串中迭代器p指向的字符,返回删除后迭代器的位置。
原型:iterator erase (const_iterator first, const_iterator last);
说明:删除源字符串迭代器范围为[first,last)内的所有字符,返回删除后迭代器的位置
#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.
POP_BACK:删除源字符串的最后一个字符,有效减少它的长度。
#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