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


当前回答

std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());

其他回答

string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
        size_t position = 0;
        for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
        {
                str.replace(position ,1, toreplace);
        }
        return(str);
}

使用它:

string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");

从gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
string removeSpaces(string word) {
    string newWord;
    for (int i = 0; i < word.length(); i++) {
        if (word[i] != ' ') {
            newWord += word[i];
        }
    }

    return newWord;
}

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

你可以使用这个解决方案来删除一个字符:

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

str.erase(remove(str.begin(), str.end(), char_to_remove), str.end());