Replace multiple spaces with one space in a string

前端 未结 5 1512
感动是毒
感动是毒 2020-12-01 03:54

How would I do something in c++ similar to the following code:

//Lang: Java
string.replaceAll(\"  \", \" \");

This code-snippe

5条回答
  •  佛祖请我去吃肉
    2020-12-01 04:40

    So, I tried a way with std::remove_if & lambda expressions - though it seems still in my eyes easier to follow than above code, it doesn't have that "wow neat, didn't realize you could do that" thing to it.. Anyways I still post it, if only for learning purposes:

    bool prev(false);
    char rem(' ');
    auto iter = std::remove_if(str.begin(), str.end(), [&] (char c) -> bool {
        if (c == rem && prev) {
            return true;
        }
        prev = (c == rem);
        return false;
    });
    in.erase(iter, in.end());
    

    EDIT realized that std::remove_if returns an iterator which can be used.. removed unnecessary code.

提交回复
热议问题