Friday, 30 January 2015

Reverse a String

void reverse(char* str)
{
    char* end = str;
   
    char tmp;
   
    if(str)
    {
        //find the end of the string
        while(end) ++end;
   
        --end; // since the last character is the null character
   
        //swap the elements starting from start and end till pointers meet in middle at same address
        while(str < end )
        {
            tmp = *str;
            *str++ = *end ;
            *end-- = tmp;
   
        }
    }
}

No comments:

Post a Comment