Interview Question : Trim multiple consecutive spaces from a string

前端 未结 11 859
情书的邮戳
情书的邮戳 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:42

    A c++0x - solution using a lambda instead of a regular function object. Compare to Cubbi's solution.

    #include 
    #include 
    
    int main()
    {
        std::string str = "I    Like    StackOverflow a      lot";
    
        str.erase(std::unique(str.begin(), str.end(),
          [](char a, char b) { return a == ' ' && b == ' '; } ), str.end() );  
    }
    

提交回复
热议问题