0

I tried to write a function that get a string with spaces and returns the string without the spaces.

for example:

str = "   a  f  ";

will be replaced to "af";

my function doesn't work, it replaced the string to: "af f".

this is my function:

void remove_space(string& str) {
    int len = str.length();
    int j = 0, i = 0;
    while (i < len) {
        while (str.at(i) == ' ') i++;
        str.at(j) = str.at(i);
        i++;
        j++;
    }
}

int main ()
{
string str;
    getline(cin, str);
    remove_space(str);
    cout << str << endl;
return 0;
}

any help appreciated!

Alon Shmiel
  • 6,753
  • 23
  • 90
  • 138

5 Answers5

3

Bounds checking!

You've forgotten to check bounds accessing in the inner loop: while (str.at(i) == ' ') i++;.

I rewrote the code :

void remove_space(string& str)
{
    int len = str.length();
    int j = 0;

    for (int i = 0; i < len;)
    {
        if (str.at(i) == ' ')
        {
            i++;
            continue;
        }

        str.at(j++) = str.at(i++);
    }
    str.resize(j);
}

Also, you can use below code to remove spaces (suggested in cppreference.com):

str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
masoud
  • 55,379
  • 16
  • 141
  • 208
2

If you can use Boost, you can do the following:

#include<boost/algorithm/string.hpp>
...
erase_all(str, " ");

Otherwise, I'd suggest this alternative:

#include<cctype>
#include<algorithm>
...
str.erase(std::remove (str.begin(), str.end(), ' '), str.end());
Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
1
#include<cctype>
#include<algorithm>

bool my_isspace(char c) {
    return std::isspace(c);
}

str.erase(remove_if(str.begin(), str.end(), my_isspace), str.end());

should do the job.


Regarding your function

void remove_spaces(string& str)
{
    int len = str.length();
    int j = 0, i = 0;

    while (j < len) 
    {
        if (str.at(i) == ' ') {
          ++j;
        }
        str.at(i) = str.at(j);
        ++i;
        ++j;
    }


    // You are missing this
    str.erase(i,len);
}
stardust
  • 5,918
  • 1
  • 18
  • 20
  • To conform to the standard it should be `isspace((unsigned)c)` or equivalent. `isspace(int)` isn't guaranteed to accept negative input. – Steve Jessop Apr 21 '13 at 18:02
1

Rather than implementing your own solution, you could use the tried and tested erase remove idiom:

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
  std::string s("a b c d e f g");
  std::cout << s << "\n";
  const char_to_remove = ' ';
  s.erase(std::remove(s.begin(), s.end(), char_to_remove), s.end() );
  std::cout << s << "\n";
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

You need to resize string after processing. E.g. add line at end of remove_space:

str.resize(j);
Danil Asotsky
  • 1,241
  • 4
  • 23
  • 29