c++去掉首尾空格是参考一篇文章的,但是忘记文章出处了,就略过吧。
去掉首尾空格的代码如下:


1 void trim(string &s) 2 { 3 4 if( !s.empty() ) 5 { 6 s.erase(0,s.find_first_not_of(" ")); 7 s.erase(s.find_last_not_of(" ") + 1); 8 } 9 10 }
去掉字符串中所有空格的代码如下:


1 void trim(string &s) 2 { 3 /* 4 if( !s.empty() ) 5 { 6 s.erase(0,s.find_first_not_of(" ")); 7 s.erase(s.find_last_not_of(" ") + 1); 8 } 9 */ 10 int index = 0; 11 if( !s.empty()) 12 { 13 while( (index = s.find(' ',index)) != string::npos) 14 { 15 s.erase(index,1); 16 } 17 } 18 19 }
测试代码如下:


1 int main() 2 { 3 4 cout << "-------------------------------------" << endl; 5 6 string pri = " 7ter 09, jdhfd iere*- ddw jjdjjdj "; 7 cout << "private string is : \"" << pri << "\"" << endl; 8 trim(pri); 9 cout << "after string is : \"" << pri << "\"" << endl; 10 11 cout << "-------------------------------------" << endl; 12 13 return 0; 14 }
结果如下图:

本文详细介绍了如何使用C++来去除字符串中的首尾空格及所有空格的方法。通过具体的代码示例,展示了两种不同的函数实现方式,一种是仅去除首尾空格,另一种则是彻底清除字符串内的所有空格。同时,提供了测试代码及其运行结果,验证了方法的有效性。
2273

被折叠的 条评论
为什么被折叠?



