Question

I have CStrings with single/multiple whitespaces in my MFC application. I have to replace them with single underscore. Example: sampleString=

"A B  C D   E" --> "A_B_C_D_E"

But when I use sampleString.Replace(" ",'_'), underscore appears for each spaces i.e.

"A_B__C_D___E".

I have written a code but didnot like it much ,also it is faulty.

                int i=0,pos=0,lastSpacePos=sampleString.GetLength();
                while(i<sampleString.GetLength())
                {
                    pos=sampleString.Find(" ",i);
                    if(pos!=-1)
                    {
                        if(lastSpacePos!=(pos-1))
                        {
                            sampleString.Delete(pos,1);
                            sampleString.Insert(pos,"_");
                        }                        
                        lastSpacePos=pos;
                        i=pos+1;
                    }
                    else
                        i++;
                }
                sampleString.Remove(' ');

Is there any simpler method that I am missing ?

Was it helpful?

Solution

Replace returns the number of characters to replace found so you can try replacing two spaces with one space until no more space pairs are found:

while(sampleString.Replace("  "," "));

And then replace one space with underscore:

sampleString.Replace(" ",'_');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top