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


当前回答

只是为了好玩,因为其他答案比这个好得多。

#include <boost/hana/functional/partial.hpp>
#include <iostream>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
int main() {
    using ranges::to;
    using ranges::views::filter;
    using boost::hana::partial;
    auto const& not_space = partial(std::not_equal_to<>{}, ' ');
    auto const& to_string = to<std::string>;

    std::string input = "2C F4 32 3C B9 DE";
    std::string output = input | filter(not_space) | to_string;
    assert(output == "2CF4323CB9DE");
}

其他回答

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

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 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, " ", "+");
string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        i++;
    }    
}

在c++ 20中,你可以使用免费函数std::erase

std::string str = " Hello World  !";
std::erase(str, ' ');

完整的例子:

#include<string>
#include<iostream>

int main() {
    std::string str = " Hello World  !";
    std::erase(str, ' ');
    std::cout << "|" << str <<"|";
}

我打印|,这样很明显,开头的空格也被删除了。

注意:这只删除空格,而不是所有其他可能被认为是空格的字符,参见https://en.cppreference.com/w/cpp/string/byte/isspace