Remove extra white spaces in C++

前端 未结 12 1834
日久生厌
日久生厌 2021-02-05 12:01

I tried to write a script that removes extra white spaces but I didn\'t manage to finish it.

Basically I want to transform abc sssd g g sdg gg gf into

12条回答
  •  灰色年华
    2021-02-05 12:25

    You can use std::unique which reduces adjacent duplicates to a single instance according to how you define what makes two elements equal is.

    Here I have defined elements as equal if they are both whitespace characters:

    inline std::string& remove_extra_ws_mute(std::string& s)
    {
        s.erase(std::unique(std::begin(s), std::end(s), [](unsigned char a, unsigned char b){
            return std::isspace(a) && std::isspace(b);
        }), std::end(s));
    
        return s;
    }
    
    inline std::string remove_extra_ws_copy(std::string s)
    {
        return remove_extra_ws_mute(s);
    }
    

    std::unique moves the duplicates to the end of the string and returns an iterator to the beginning of them so they can be erased.

    Additionally, if you must work with low level strings then you can still use std::unique on the pointers:

    char* remove_extra_ws(char const* s)
    {
        std::size_t len = std::strlen(s);
    
        char* buf = new char[len + 1];
        std::strcpy(buf, s);
    
        // Note that std::unique will also retain the null terminator
        // in its correct position at the end of the valid portion
        // of the string    
        std::unique(buf, buf + len + 1, [](unsigned char a, unsigned char b){
            return (a && std::isspace(a)) && (b && std::isspace(b));
        });
    
        return buf;
    }
    

提交回复
热议问题