Question:
How do I remove multiple spaces from a cstring (character string) in c++?
2007-11-09 18:27:05 UTC
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.
Three answers:
gene_frequency
2007-11-10 09:00:42 UTC
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 >= songlist_count)

done = 1;

break;



default:

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

break;

}

lastCh =ch;

}

}
?
2016-11-05 04:06:57 UTC
Cstring Remove
?
2016-10-02 04:20:19 UTC
contain utilising namespace std; int important (void) { char String[] = "hi How Are You?"; char Buffer[255]; unsigned int len = strlen(String);// get string length. int i; int zz = 0; // merely reproduction printable and no area characters to buffer. for(i = 0; i < len; i++) { if(isprint(String[i]) && !isspace(String[i])) { Buffer[zz] = String[i]; zz++; } } // Insert NULL terminating byte. Buffer[zz] = 0; // show string. cout << Buffer << endl; // return to working device. return 0; } // end OF important software BLOCK


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...