string::erase的三种函数原形
1、iterator erase(iterator _First, iterator _Last);
2、iterator erase(iterator _It);
3、basic_string& erase(size_type _Pos = 0,size_type _Count = npos);
一般的对于需要删除字符串开始和结尾的空格的代码,经常为
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 void main()
6 {
7 string strTest="Hello, world.";
8
9 strTest.erase(0, strTest.find_first_not_of(' '));
10 cout << "[" << strTest << "]" << endl;
11
12 strTest.erase(strTest.find_last_not_of(' ')+1);
13 cout << "[" << strTest << "]" << endl;
14 }
2 #include <string>
3 using namespace std;
4
5 void main()
6 {
7 string strTest="Hello, world.";
8
9 strTest.erase(0, strTest.find_first_not_of(' '));
10 cout << "[" << strTest << "]" << endl;
11
12 strTest.erase(strTest.find_last_not_of(' ')+1);
13 cout << "[" << strTest << "]" << endl;
14 }
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 void main()
6 {
7 string strTest=" Hello, world. ";
8
9 strTest.erase(0, strTest.find_first_not_of(' '));
10 cout << "[" << strTest << "]" << endl;
11
12 strTest.erase(strTest.find_last_not_of(' ')+1);
13 cout << "[" << strTest << "]" << endl;
14
15 string strTest="Hello, world.";
16
17 strTest.erase(0, strTest.find_first_not_of(' '));
18 cout << "[" << strTest << "]" << endl;
19
20 strTest.erase(strTest.find_last_not_of(' ')+1);
21 cout << "[" << strTest << "]" << endl;
22 }
2 #include <string>
3 using namespace std;
4
5 void main()
6 {
7 string strTest=" Hello, world. ";
8
9 strTest.erase(0, strTest.find_first_not_of(' '));
10 cout << "[" << strTest << "]" << endl;
11
12 strTest.erase(strTest.find_last_not_of(' ')+1);
13 cout << "[" << strTest << "]" << endl;
14
15 string strTest="Hello, world.";
16
17 strTest.erase(0, strTest.find_first_not_of(' '));
18 cout << "[" << strTest << "]" << endl;
19
20 strTest.erase(strTest.find_last_not_of(' ')+1);
21 cout << "[" << strTest << "]" << endl;
22 }
结论
1、只有第3种函数原形被调用。
2、凑巧的是,当 strTest.find_last_not_of(' ')返回 string::npos的时候,对其加1恰好不会引起任何的副作用。string::npos被定义为-1,所以当strTest.find_last_not_of(' ')返回-1的时候正好需要删除0个字符。这种巧合尽管缩短了代码,但是却导致不易被理解.
3、size_type显然是从1开始计数的,既如果第一个字符就是目的字符,那么find_xxx函数返回1。
分类:
STL/Boost學習
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具