facebook like button

06 December, 2011

program to reverse the order of words in a sentence

The need:
     I don't know what could be the need of this program but I found this question on many sites and thats why I wrote this program.This program is extension of previous program.
The code:
----------------------------------------------------------
#include<stdio.h>
#include<string.h>

void reverse(char *str,int start, int end)
{
    char temp;
    int i,j;
    i=end-start;
    for(j=0;j<=i/2;j++)
    {      
        temp=*(str+start+j);
        *(str+start+j)=*(str+start+i-j);
        *(str+start+i-j)=temp;
    }
}

rev_word(char *str)
{
    int start=0,end=0,i=0;  
    while(*(str+i)!='\0')
    {
        if(*(str+i)==' ')
        {
            end=i-1;
            reverse(str, start, end);
            i++;
            start=i;
        }
        else
            i++;
    }
    end=i-1;
    reverse(str, start, end);
}

int main()
{
    char a[]="I dont know why useless programs are asked";
    printf("before\n%s\n",a);
    rev_word(a);
    reverse(a, 0, strlen(a)-1);
    printf("after\n%s\n",a);
    return 0;
}
----------------------------------------------------------
Approach:
   The approach is simple. make a note of start and end points (indices) of each word and reverse with the help of those points. The UDF reverse() does the job here. After that reverse the whole sentence character by character. I have used my UDF here because its existing and I dont need to write or search for another function though one could also use strrev() built-in function to reverse the whole sentence character by character.
Remarks:
1. You can modify reverse() function here into ordinary string_reverse (same as built-in strrev) function. For that remove arguments start and end from the function definition and use 0 in place of start and (length of string-1) as end.
Other approach:
2. Here for doing the whole thing I have used only one extra character other than the provided string (off course I have also used counters etc. but that is different thing). If I was allowed to use as much space as I wanted, I would have not thought this much like I have thought here --> reversing the spelling of each word and then reversing the whole string. In that case I would have made use of my stack concepts and using almost no brain I could have got it done. Have a look how simple is this. Steps are:
1. read word by word (using scanf with %s)
2. keep on pushing all words on a stack till last word.
3. Now pop each word and print. :-)
For this approach have a look at next program on this topic.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply