Mar 31, 2012

Reverse the words of a string

Given a string My name is Antonio Gonsalves. You have to reverse all the letters of the words in the string so that the resultant string looks like yM eman si oinotnA sevlasnoG

int main()
{
    char str[] = "My name is Antonio Gonsalves", 
         *startPtr = str,
         *endPtr = str,
         *spacePtr;

    while(*spacePtr != '\0')
    {
        while(*endPtr != ' ' && *endPtr != '\0')
            ++endPtr;

        spacePtr = endPtr;
        endPtr = spacePtr - 1;
       
        char temp;
        while(startPtr < endPtr)
        {
            temp = *endPtr;
            *endPtr-- = *startPtr;
            *startPtr++ = temp;
        }
        
        startPtr = spacePtr + 1;
        endPtr = spacePtr + 1;
    }
    printf("%s\n", str);
    return 0;
}
$ ./a.out 
yM eman si oinotnA sevlasnoG

No comments :

Post a Comment