reverse word in a string

 

 

void reverseWordinString( char *s )
{
    char *p1, *p2;
    p1 =  p2 = s;
    while( *p2 != '' )
    {
        p2++;
    }
    // you are one step ahead
    p2--;

    // invert the whole string
    reverse( p1, p2 );

    // then need to reverse each word
    p2 = s;
    while( 1 )
    {
        while( *p2 != ' ' )
        {
            p2++;
        }
        p2--;

        if( *p2 == '' )
        {
            return;
        }
        reverse( p1, p2 );

        while( *++p2 == ' ' )
        p2++;
        p1 = p2;
    }

}

void reverse( char *pBegin, *pEnd )
{
    if( *pBegin == NULL || *pEnd == NULL )
    {
        return NULL;
    }
    char *temp;

    for(; pBegin <= pEnd; pBegin++, pEnd-- )
    {
        *temp = *pBegin;
        *pBegin = *pEnd;
        *pEnd =  *temp;
    }

}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s