Help me to clear multiple spaces.

Hi all,

1
2
3
4
5
6
7
8
9
10
11
12
int i;

void f3(string& text3){
	for(i = 0;i < text3.length(); i++){
		do{
				string s(text3.begin(),text3.begin() + (i));
				string t(text3.begin()+ (i+1), text3.end());
  			  	text3 = s + t;
  			  	i++;
		} while ((text3[i] == ' ') && (text3[i+1] == ' '));
	}
}


This is my code for clearing spaces. I do not want to use string.erase().

It just worked in the case I have 2 spaces between 2 character. On the other case, it juts clears only 1 space. I don't know why?

Can someone explain it to me?

Thanks
look at line 10
If I has "This is my code_____blabla." -> "This is my code____blabla." ( _ = space)

The for loop seems to run once.
Last edited on
http://www.cplusplus.com/doc/tutorial/control/

scroll down till you reach "The do-while loop"
1
2
3
4
5
6
7
8
9
void f3(string& text3){
	for(i = 0;i < text3.length(); i++){
		if ((text3[i] == ' ') && (text3[i+1] == ' ')){
				string s(text3.begin(),text3.begin() + (i));
				string t(text3.begin()+ (i+1), text3.end());
  			  	text3 = s + t;
		}
	}
}


Is it the same as the above ?.
no, it's not and if-else is also explained in the link i posted, but since you are too lazy to read it.

do while stops if the statement inside while() is true
if starts if the statement inside if() is true
Last edited on
Yeah, I know, but I still stuck in this error.

"This is my______code." -> "This is my_____code." (_ = space)

It just clear 1 space.

You know what I mean? The for loop seems running once ~X(((((((, oh my godness
you should really learn how to use a debugger

line 4 string s(text3.begin(),text3.begin() + (i)); creates a string named s containing 0 times the ascii sign with the number i

line 5 is also wrong

this should help you http://www.cplusplus.com/reference/string/string/string/
Last edited on
I know the solution.

Thank you. ^^
tsangz,

you could be getting into problems if you're constantly changing i, AND changing the length of text3 at the same time. you're using text3 for too many things: a storage of the result, as a length, and a source for the string copy. I would create a separate string to hold the result of the string copy while you do comparisons on text3.

also, the first iteration of your loop changes the first character of the string all the time, you should reverse it to a while() {} loop instead of a do{} loop.

you could even try something like this:
1
2
3
4
5
6
7
8
9
10
11
    string output;
    output = "";
    for(int i = 0; i < text3.length(); i++)
    {
        output = output + text3[i];
        while ((text3[i] == ' ') & text3[i+1]== ' '  )
        {
            i++;
        }
    }
    text3 = output;
Your solution is better than mine.

Thank a lots. You help me a lots, not only in this problem :D
Topic archived. No new replies allowed.