当前位置:首页 > 通信资讯 > 正文

c++去掉字符串首尾空格(c++ string去掉前后空格)

本文实例讲述了c++ String去除头尾空格的方法,分享给大家供大家参考。具体实现方法如下:

实现该功能可使用string的find_first_not_of,和find_last_not_of方法,具体实现带如下:

复制代码 代码如下:

#include <iostream>
#include <string>

std::string& trim(std::string &);

int main()
{
std::string s = " Hello World!! ";
std::cout << s << " size:" << s.size() << std::endl;
std::cout << trim(s) << " size:" << trim(s).size() << std::endl;

return 0;
}

std::string& trim(std::string &s)
{
if (s.empty())
{
return s;
}

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

希望本文所述对大家的C++程序设计有所帮助。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。