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


当前回答

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

    return newWord;
}

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

其他回答

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, " ", "+");

恐怕这是我能想到的最好的解决办法了。但是您可以使用reserve()预先分配所需的最小内存,从而稍微加快速度。你最终会得到一个新的字符串,它可能会更短,但占用相同数量的内存,但你将避免重新分配。

编辑:根据您的情况,这可能会比混淆字符产生更少的开销。

您应该尝试不同的方法,看看哪种方法最适合您:您可能根本没有任何性能问题。

std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        i++;
    }    
}

从gamedev

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