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


当前回答

我使用下面的工作周围很长时间-不确定它的复杂性。

s.erase (std::独特(s.begin (), s.end(),[](字符,字符f){返回(f = = ' ' | | ==' ');}), s.end ());

当你想删除字符' '和一些例如-使用

s . wipe (std:: unique (s .(初),s . end (), [] (char s, char (f) {return ((f = = ' | | s = = ' ') | | (f = = ' - ' | | s =='-'));}), s end ());

同样,如果你想删除的字符数量不是1,只需要增加||

但是正如其他人所提到的,“删除”这个习语似乎也不错。

其他回答

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, " ", "+");
string removeSpaces(string word) {
    string newWord;
    for (int i = 0; i < word.length(); i++) {
        if (word[i] != ' ') {
            newWord += word[i];
        }
    }

    return newWord;
}

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

我创建了一个函数,从字符串的两端移除空白。如 “Hello World”,将转换为“Hello World”。

这类似于python中经常使用的strip、lstrip和rstrip函数。

string strip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string lstrip(string str) {
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string rstrip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    return str;
}

如果你想用一个简单的宏来做到这一点,这里有一个:

#define REMOVE_SPACES(x) x.erase(std::remove(x.begin(), x.end(), ' '), x.end())

当然,这假设您已经执行了#include <string>。

这样称呼它:

std::string sName = " Example Name ";
REMOVE_SPACES(sName);
printf("%s",sName.c_str()); // requires #include <stdio.h>

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

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

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