Remove extra white spaces in C++

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

    Since you use C++, you can take advantage of standard-library features designed for that sort of work. You could use std::string (instead of char[0x255]) and std::istringstream, which will replace most of the pointer arithmetic.

    First, make a string stream:

    std::istringstream stream(input);
    

    Then, read strings from it. It will remove the whitespace delimiters automatically:

    std::string word;
    while (stream >> word)
    {
        ...
    }
    

    Inside the loop, build your output string:

        if (!output.empty()) // special case: no space before first word
            output += ' ';
        output += word;
    

    A disadvantage of this method is that it allocates memory dynamically (including several reallocations, performed when the output string grows).

提交回复
热议问题