Tuesday, December 8, 2009

Reverse Words

/*
Function that reverses the order of the words in a string. For example, function should transform the string “Do or do not, there is no try.” to “try. no is there not, do or Do”.
*/
void reverseWords( char str[] )
{
    int start = 0, end = 0, length;

    length = strlen(str);
    /* Reverse entire string */
    reverseString(str, start, length - 1);

    while( end < length )
    {
       if( str[end] != ' ' )
       { /* Skip non-word characters */

           /* Save position of beginning of word */
           start = end;

           /* Scan to next non-word character */
           while( end < length && str[end] != ' ' )
               end++;
            /* Back up to end of word */
            end--;

            /* Reverse word */
            reverseString( str, start, end );
        }
        end++; /* Advance to next token */
    }
}

void reverseString( char str[], int start, int end )
{
    char temp;
    while( end > start )
    {
        /* Exchange characters */
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;

        /* Move indices towards middle */
        start++; end--;
    }
}

No comments:

Post a Comment