Remove extra white spaces in C++

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

    There are plenty of ways of doing this (e.g., using regular expressions), but one way you could do this is using std::copy_if with a stateful functor remembering whether the last character was a space:

    #include 
    #include 
    #include 
    
    struct if_not_prev_space
    {
        // Is last encountered character space.
        bool m_is = false;
    
        bool operator()(const char c)
        {                                      
            // Copy if last was not space, or current is not space.                                                                                                                                                              
            const bool ret = !m_is || c != ' ';
            m_is = c == ' ';
            return ret;
        }
    };
    
    
    int main()
    {
        const std::string s("abc  sssd g g sdg    gg  gf into abc sssd g g sdg gg gf");
        std::string o;
        std::copy_if(std::begin(s), std::end(s), std::back_inserter(o), if_not_prev_space());
        std::cout << o << std::endl;
    }
    

提交回复
热议问题