Remove extra white spaces in C++

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

    There are already plenty of nice solutions. I propose you an alternative based on a dedicated meant to avoid consecutive duplicates: unique_copy():

    void remove_extra_whitespaces(const string &input, string &output)
    {
        output.clear();  // unless you want to add at the end of existing sring...
        unique_copy (input.begin(), input.end(), back_insert_iterator(output),
                                         [](char a,char b){ return isspace(a) && isspace(b);});  
        cout << output<

    Here is a live demo. Note that I changed from c style strings to the safer and more powerful C++ strings.

    Edit: if keeping c-style strings is required in your code, you could use almost the same code but with pointers instead of iterators. That's the magic of C++. Here is another live demo.

提交回复
热议问题