Friday, October 4, 2013

C Program To Perform Reversal Of A String IN PLACE

Approach:

The trick behind this is very simple maintain two pointers one end pointer and one start pointer and swap their contents iteratively till they meet each other.

Let’s try to code it:

Program:

#include<stdio.h> /*for printf and scanf*/

void InplaceRev(char* str)
{
    char* temp=str; // end pointer
    char var;
    if(str==NULL)
       return str ;
    while(*temp)
        temp++; /*temp is pointing to '\0' i.e. end of string*/

    temp--; /*temp decremented to point to the last character of the string*/
    while(str<temp) // run a loop till the start and end pointer meet
    {
        var=*str;
        *str++=*temp;
        *temp--=var;
    }
}

int main()
{
    char str[]="THIS IS IT..";
    char* temp=str;
    printf("Original String is:\n%s\n\n",str);
    printf("String after reversal is : \n");
    InplaceRev(temp);
    printf("%s",temp);
    return 0;
}

Viva La Raza
Sid

No comments:

Post a Comment