去除字符串的空格,C#里面直接使用trim()函数,C++里需要进行一些处理,这里介绍几种方法
一、去除前空格
方案1
string str = " sshah hha ";
str.erase(str.begin(), std::find_if(str.begin(), str.end(),
std::not1(std::ptr_fun(::isspace))));
cout << str << endl;
方案2
string str = " sshah hha ";
str.erase(0, str.find_first_not_of(" "));
std::cout << str << std::endl;
二、去除后空格
方案1
string str = " sshah hha ";
str.erase(std::find_if(str.rbegin(), str.rend(),
std::not1(std::ptr_fun(::isspace))).base(),str.end());
cout << str << endl;
方案2
string str = " sshah hha ";
str.erase(str.find_last_not_of(" ") + 1);
std::cout << str << std::endl;
三、去除前后空格
方案1
string word = " sshah hha ";
std::string::iterator end_pos = std::remove(word.begin(), word.end(), ' ');
word.erase(end_pos, word.end());//移除空格
cout << word << endl;
方案2
#include <algorithm>
#include <functional>
#include <iterator>
#include <string>
string word = " sshah hha ";
remove_if(word.begin(), word.end(), isspace);
cout << word << endl;
参考:
https://www.imooc.com/wenda/detail/578420
https://bbs.csdn.net/topics/370023430