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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How this works. The
std::uniquehas 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 withstd::unique, duplicate adjacent spaces are removed.Just like
std::removeandremove_if,std::uniquedoesn’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 theerasefunction, 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.