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


当前回答

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

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

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

其他回答

对于微调,使用boost字符串算法:

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

string str1(" hello world! ");
trim(str1);      // str1 == "hello world!"

最好的方法是使用算法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;
}

删除所有空白字符,如制表符和换行符(c++ 11):

string str = " \n AB cd \t efg\v\n";
str = regex_replace(str,regex("\\s"),"");
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, " ", "+");

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

#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");
}