Interview Question : Trim multiple consecutive spaces from a string

前端 未结 11 827
情书的邮戳
情书的邮戳 2020-12-08 17:34

This is an interview question Looking for best optimal solution to trim multiple spaces from a string. This operation should be in-place operation.

input  =          


        
11条回答
  •  感情败类
    2020-12-08 17:44

    Does using qualify as "algorithmic solution"?

    #include 
    #include 
    #include 
    #include 
    struct BothAre
    {
        char c;
        BothAre(char r) : c(r) {}
        bool operator()(char l, char r) const
        {
                return r == c && l == c;
        }
    };
    int main()
    {
        std::string str = "I    Like    StackOverflow a      lot";
        std::string::iterator i = unique(str.begin(), str.end(), BothAre(' '));
        std::copy(str.begin(), i, std::ostream_iterator(std::cout, ""));
        std::cout << '\n';
    }
    

    test run: https://ideone.com/ITqxB

提交回复
热议问题