Remove extra white spaces in C++

前端 未结 12 1833
日久生厌
日久生厌 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:18

    for in-place modification you can apply erase-remove technic:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::string input {"asfa sas    f f dgdgd  dg   ggg"};
        bool prev_is_space = true;
        input.erase(std::remove_if(input.begin(), input.end(), [&prev_is_space](unsigned char curr) {
            bool r = std::isspace(curr) && prev_is_space;
            prev_is_space = std::isspace(curr);
            return r;
    
        }), input.end());
    
        std::cout << input << "\n";
    }
    

    So you first move all extra spaces to the end of the string and then truncate it.


    The great advantage of C++ is that is universal enough to port your code to plain-c-static strings with only few modifications:

    void erase(char * p) {
        // note that this ony works good when initial array is allocated in the static array
        // so we do not need to rearrange memory
        *p = 0; 
    }
    
    int main()
    {
        char input [] {"asfa sas    f f dgdgd  dg   ggg"};
        bool prev_is_space = true;
        erase(std::remove_if(std::begin(input), std::end(input), [&prev_is_space](unsigned char curr) {
            bool r = std::isspace(curr) && prev_is_space;
            prev_is_space = std::isspace(curr);
            return r;
    
        }));
    
        std::cout << input << "\n";
    }
    

    Interesting enough remove step here is string-representation independent. It will work with std::string without modifications at all.

提交回复
热议问题