Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview Question : Trim multiple consecutive spaces from a string

Tags:

c++

c

string

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  = "I    Like    StackOverflow a      lot"
output = "I Like StackOverflow a lot"

String functions are not allowed, as this is an interview question. Looking for an algorithmic solution of the problem.

like image 675
Unicorn Avatar asked Apr 06 '11 03:04

Unicorn


People also ask

What does consecutive spaces mean?

Consecutive comes from the Latin consecutus, meaning "following closely" with no gap. Just like those snowstorms — one storm happened each day, back to back, for five days in a row. Consecutive numbers also follow each other, or advance in the right order. For example, 5, 6, 7, 8, 9, 10 are consecutive numbers.

How do you remove multiple spaces in a string in C++?

Remove spaces from std::string in C++ To remove this we will use the remove() function. With this remove() function it takes the beginning and end of the iterator, then takes the third argument that will be deleted from that iterator object.

How do you trim a string in C++?

The trimming string means removing whitespaces from left and right part of the string. To trim the C++ string, we will use the boost string library. In that library, there are two different methods called trim_left() and trim_right(). To trim string completely, we can use both of them.


1 Answers

Does using <algorithm> qualify as "algorithmic solution"?

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
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<char>(std::cout, ""));
    std::cout << '\n';
}

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

like image 65
Cubbi Avatar answered Sep 21 '22 22:09

Cubbi