Thursday, July 30, 2009

How do I remove multiple spaces from a cstring (character string) in c++?

For example


If I have a two dimmensional character array string: songdata[x][y]. and it contains the characters "the great escape". How do I manipulate it to make it look like:


"the great escape"





I just want to remove spaces where there are multiple spaces, but not remove all of the spaces.

How do I remove multiple spaces from a cstring (character string) in c++?
Seasoned programmers will want to howl at me on this code because we're building the replacement string into the same buffer (songlist[x][y]) as the source buffer--(not using a temporary buffer)....generally a bad practice.





However, this code works (and is extremely efficient) because--in this instance--the resulting string is guaranteed to be the same len, or shorter, than the source string. A little thought on this will prove it out.





Best wishes,





_g








void strip_excess_space(int songlist_count)


{


int x=0, y=0, z=0;


int done=0;


int ch, lastCh=' ';





while(!done)


{


ch = songdata[x][y++];


switch(ch)


{


case ' ': //a space?


if(lastCh != ch) //if last character wasn't a space...


songdata[x][z++] = ch; //permit it.


break;





case '\0': //end of string


songdata[x][z++] = ch;


x++; //go to next name in songlist


z=y=0; //...and beginning of buffers


//check for end


if(x %26gt;= songlist_count)


done = 1;


break;





default:


songdata[x][z++] = ch;


break;


}


lastCh =ch;


}


}


No comments:

Post a Comment