在c++中,从字符串中删除空格的首选方法是什么?我可以循环遍历所有字符,并建立一个新的字符串,但有更好的方法吗?


当前回答

# include <算法> 使用命名空间std; Int main() { . . s.erase(删除(s.begin (), s.end (), ' ' ), s.end ()); . . }


来源:

参考资料来自本论坛。

其他回答

对于微调,使用boost字符串算法:

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

string str1(" hello world! ");
trim(str1);      // str1 == "hello world!"
  string str = "2C F4 32 3C B9 DE";
  str.erase(remove(str.begin(),str.end(),' '),str.end());
  cout << str << endl;

输出:2 cf4323cb9de

你能使用Boost String算法吗?http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573

erase_all(str, " "); 
string removeSpaces(string word) {
    string newWord;
    for (int i = 0; i < word.length(); i++) {
        if (word[i] != ' ') {
            newWord += word[i];
        }
    }

    return newWord;
}

这段代码基本上接受一个字符串并遍历其中的每个字符。然后检查该字符串是否为空白,如果不是,则将该字符添加到新字符串中。

从gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());