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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With