Friday, November 15, 2013

Program to reverse words in a given string

Today's post is all about reversing strings. Without feeling the need to mention the algorithm, I am jumping straight to code after an example.

Input string: "This is yoyo honey singh"
output: "singh honey yoyo is This"

Here's the implementation:

#include<stdio.h>
#include<stdlib.h>

void reverse(char* str);
void reverse_wrds(char*str1,char*str2);

void reverse(char* s)
{
    char* temp=s;
    char* beg=s;

    while(*temp)
    {
        temp++;
        if(*temp == '\0')
        {
            reverse_wrds(beg,temp-1);
        }
        if(*temp ==' ')
        {
            reverse_wrds(beg,temp-1);
            beg=temp+1;
        }
    }
reverse_wrds(s,temp-1);
}

void reverse_wrds(char* beg,char* end)
{
    char temp;
    while(beg<end)
    {
        temp=*beg;
        *beg++=*end;
        *end--=temp;

    }
}

int main()
{
    char s[]="This is yoyo honey singh";
    char* temp=s;
    reverse(temp);
    puts(temp);
}

This code to handle cases where starting of the string or in the the middle there are extra spaces a slight modification is required. Here's the pseudo code for that:

beg=NULL;
while(*temp)
{
if(beg==NULL && *temp!=' ' )
{
beg=temp;
}

if(beg!=NULL&& (*temp+1==' '|| *temp+1='\0'))
{
reverse_wrds(beg,temp);
beg=NULL;
}
reverse(the whole string)
}

Viva La Raza
Sid


No comments:

Post a Comment