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 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.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
参考文献:
[1] 网络资源:
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/
————————————————
版权声明:本文为CSDN博主「Cainv89」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cainv89/article/details/48102991