What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?
Share
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.
The best thing to do is to use the algorithm
remove_ifand isspace:Now the algorithm itself can’t change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:
We should also note that remove_if will make at most one copy of the data. Here is a sample implementation: