Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple spaces with one space in a string

How would I do something in c++ similar to the following code:

//Lang: Java string.replaceAll("  ", " "); 

This code-snippet would replace all multiple spaces in a string with a single space.

like image 626
evenodd Avatar asked Dec 02 '11 20:12

evenodd


People also ask

How do I replace multiple spaces with a single space in Python?

Use the re. sub() method to replace multiple spaces with a single space, e.g. result = re. sub(' +', ' ', my_str) .

How do I remove multiple spaces from a string?

Using regexes with "\s" and doing simple string. split()'s will also remove other whitespace - like newlines, carriage returns, tabs.

How do I replace multiple spaces with single space in bash?

Continuing with that same thought, if your string with spaces is already stored in a variable, you can simply use echo unquoted within command substitution to have bash remove the additional whitespace for your, e.g. $ foo="too many spaces."; bar=$(echo $foo); echo "$bar" too many spaces.


1 Answers

bool BothAreSpaces(char lhs, char rhs) { return (lhs == rhs) && (lhs == ' '); }  std::string::iterator new_end = std::unique(str.begin(), str.end(), BothAreSpaces); str.erase(new_end, str.end());    

How this works. The std::unique has two forms. The first form goes through a range and removes adjacent duplicates. So the string "abbaaabbbb" becomes "abab". The second form, which I used, takes a predicate which should take two elements and return true if they should be considered duplicates. The function I wrote, BothAreSpaces, serves this purpose. It determines exactly what it's name implies, that both of it's parameters are spaces. So when combined with std::unique, duplicate adjacent spaces are removed.

Just like std::remove and remove_if, std::unique doesn't actually make the container smaller, it just moves elements at the end closer to the beginning. It returns an iterator to the new end of range so you can use that to call the erase function, which is a member function of the string class.

Breaking it down, the erase function takes two parameters, a begin and an end iterator for a range to erase. For it's first parameter I'm passing the return value of std::unique, because that's where I want to start erasing. For it's second parameter, I am passing the string's end iterator.

like image 123
Benjamin Lindley Avatar answered Sep 30 '22 08:09

Benjamin Lindley