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


当前回答

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

输出:2 cf4323cb9de

其他回答

最好的方法是使用算法remove_if和isspace:

remove_if(str.begin(), str.end(), isspace);

现在算法本身不能改变容器(只能修改值),所以它实际上会打乱值,并返回一个指针,指向现在应该结束的位置。所以我们必须调用string::erase来修改容器的长度:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

我们还应该注意,remove_if最多只生成一个数据副本。下面是一个示例实现:

template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
    T dest = beg;
    for (T itr = beg;itr != end; ++itr)
        if (!pred(*itr))
            *(dest++) = *itr;
    return dest;
}

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

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

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

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

#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,只需要增加||

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

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

erase_all(str, " ");