C++ 去掉字符串的首尾空格和全部空格



#include <iostream>
#include <string>
using namespace std;


//去掉收尾空格
string& ClearHeadTailSpace(string &str)   
{  
if (str.empty())   
{  
return str;  
}  

str.erase(0,str.find_first_not_of(" "));  
str.erase(str.find_last_not_of(" ") + 1);  
return str;  
}  


//去掉字符串中的全部空格
string& ClearAllSpace(string &str)
{
    int index = 0;
    if( !str.empty())
    {
        while( (index = str.find(' ',index)) != string::npos)
        {
            str.erase(index,1);
        }
    }

return str;
}


int main()
{
string str = "  123   456  789   ";

cout << ClearHeadTailSpace(str) << endl;
cout << ClearAllSpace(str) << endl;

system("pause");
return 0;
}
————————————————

原文链接:https://blog.csdn.net/yao_hou/article/details/78840723


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM