简体   繁体   中英

Remove spaces from a string in C++

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?

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;
}

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.

Let's assume your input has a double space, for example "c++[ ][ ]is[ ]fun" ( [ ] represents a single space). The first space has index 3 (numeration starts from 0) and the second space, is of course index 4.

In your for loop, when you hit i == 3 you erase the first space. The next iteration of the loop takes i == 4 as the index. But is the second space at index 4 now ? No! Removing the first space changed the string into "c++[ ]is[ ]fun": the space to remove is at index 3, again!

The solution can be to remove spaces right-to-left:

for (int i = length-1; i >= 0; --i) {
   if(input[i] == ' ')
      input.erase(i, 1);
}

This solution has the benefit of being simple, but as Tony D points out, it's not efficient.

this should also work -- std::replace( input.begin(), input.end(), ' ', ''); You need to include <algorithm>

this code should work

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

Reason: if it gets space in the string it will reduce the length of the string, so you have to change the variable: "length" accordingly.

I tried to write something to. This function take a string and copy to another temporary string all the content without extra spaces.

std::string trim(std::string &str){
int i = 0;
int j = 0;
int size = str.length();
std::string newStr;
bool spaceFlag = false;

for(int i = 0;i < size; i++){
    if(str[i] == ' ' && (i+1) < size && str[i+1] == ' '){
        i++;
        spaceFlag = true;
        continue;
    }       
    if(str[i] == ' '){
        newStr += " ";
        continue;
    }
    if(str[i] == '\t' && i != 0){
        str[i] = ' ';
        newStr += " ";
    }
    else{
        newStr += str[i];
        if(spaceFlag){
            newStr += " ";
            spaceFlag = false;
        }
    }
}
str = newStr;

return str;

}

#include<iostream>
#include<string.h>
using namespace std;

void trimSpace(char s[])
{
    int i=0, count=0, j=0;

    while(s[i])
    {
        if(s[i]!=' ')
            s[count++]=s[i++];
        else {
            s[count++]=' ';

            while(s[i]==' ')
                i++;
        }       
    }   

    s[count]='\0';
    cout<<endl<<"  Trimmed String : ";  
    puts(s);
}

int main()
{
    char string[1000];
    cout<<"  Enter String : ";
    gets(string);
    trimSpace(string);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM