C++基础---string类的clear/erase/pop_back

1. string类的clear/erase/pop_back

1.1 std::string::clear

    原型:void clear() noexcept; 说明:将字符串的内容清空,让源字符串成为一个空字符串(长度为0个字符)。 代码示例: #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 源字符串已被清空 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

1.2 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. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

1.3 std::string::pop_back

    原型:void 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 转载地址:http://blog..net/cainv89/article/details/48102991
经验分享 程序员 微信小程序 职场和发展