Interview Question : Trim multiple consecutive spaces from a string

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

    I'd just go with this:

    int main(int argc, char* argv[])
    {
        char *f, *b, arr[] = "  This        is    a test.                ";
        f = b = arr;
    
        if (f) do
        {
            while(*f == ' ' && *(f+1) == ' ') f++;
        } while (*b++ = *f++);
    
        printf("%s", arr);
    
        return 0;
    }
    

提交回复
热议问题