Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces from a string in C++

Tags:

c++

string

I am currently learning C++. I am trying to code a method to remove white spaces form a string and return the string with no spaces This is my code:

string removeSpaces(string input)
{
  int length = input.length();
  for (int i = 0; i < length; i++) {
     if(input[i] == ' ')
        input.erase(i, 1);
  }
  return input
}

But this has a bug as it won't remove double or triple white spaces. I found this on the net

s.erase(remove(s.begin(),s.end(),' '),s.end());

but apparently this is returning an iterator (if I understand well) Is there any way to convert the iterator back to my string input? Most important is this the right approach?

like image 754
mikey Avatar asked May 02 '13 02:05

mikey


People also ask

How do you remove spaces from a string?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

How do you remove spaces before a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.


2 Answers

std::string::erase returns an iterator, but you don't have to use it. Your original string is modified.

string removeSpaces(string input)
{
  input.erase(std::remove(input.begin(),input.end(),' '),input.end());
  return input;
}
like image 141
Vaughn Cato Avatar answered Oct 14 '22 10:10

Vaughn Cato


std::remove_if along with erase would be much easier (see it live):

input.erase(remove_if(input.begin(), input.end(), isspace),input.end());

using std::isspace had the advantage it will capture all types of white space.

like image 41
Shafik Yaghmour Avatar answered Oct 14 '22 10:10

Shafik Yaghmour