Cannot remove spaces from std string

Posted this in the wrong subforum, sorry.

I need to remove commas and spaces from string but following is only removing commas:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   string b = "1, 2, 3, 4, 5";


    for (int q=0;q<b.length();q++)

    {
        if (b[q] == ',' || b[q] == ' ')

        {
            b.erase (q,1);

        }

    }

When you erase a comma, you are moving every letter remaining in the string to the left one element. You are then moving ahead one element because of your q++, and thus your code is jumping over the next letter (i.e. the space) when a comma is deleted.

You should have worked this out for yourself like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
string b = "1, 2, 3, 4, 5";
    for (int q=0;q<b.length();q++)

    {
        cout << "b[q] is " << b[q] << endl;
        if (b[q] == ',' || b[q] == ' ')

        {
            b.erase (q,1);

        }

    }


Here is how to fix it:
1
2
3
4
5
6
7
8
9
10
11
    string b = "1, 2, 3, 4, 5";
    for (int q=0;q<b.length();)

    {
        
        if (b[q] == ',' || b[q] == ' ')
        {
            b.erase (q,1);
        }
         else {q++;}
    }

Last edited on
Ah I feel very stupid now.

Thanks!
Topic archived. No new replies allowed.