Reversing words from a string( containin more than one words separated by space – etc)

bool reverseWords( char str[] ){
char *buffer;
int tokenReadPos, wordReadPos, wordEnd, writePos = 0;

/* Position of the last character is length – 1 */
tokenReadPos = strlen(str) – 1;

buffer = (char *) malloc(tokenReadPos + 2);
if( !buffer )
return false; /* reverseWords failed */

while( tokenReadPos >= 0 ){

if( str[tokenReadPos] == ‘ ‘ ){ /* Non-word characters */
/* Write character */
buffer[writePos++] = str[tokenReadPos--];

} else { /* Word characters */
/* Store position of end of word */
wordEnd = tokenReadPos;

/* Scan to next non-word character */
while( tokenReadPos >= 0 && str[tokenReadPos] != ‘ ‘ )
tokenReadPos–;

/* tokenReadPos went past the start of the word */
wordReadPos = tokenReadPos + 1;

/* Copy the characters of the word */
while( wordReadPos <= wordEnd ){
buffer[writePos++] = str[wordReadPos++];
}
}
}
/* null terminate buffer and copy over str */
buffer[writePos] = ‘\0′;
strcpy(str, buffer);

free(buffer);

return true; /* ReverseWords successful */
}

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>