Swap words in sentence

on Sunday, November 22, 2009

A sentence is given and 2 indexes x and y. Write a code should swap word x with word y in the sentence.
eg. "I love the questions on this blog" x=2,y=6 Ans="I this the questions on love blog"












SOLUTION

char *fun(char *s,int x,int y){
int i=1,l1=0, l2=0;
char *str=s, *p1,*p2;
if ( x greater-than y ) swap (x,y);
//find position of first word
while ( i less-than x){
if ( *str == ' ')
i++;
str++;
}
p1 = str;
//length of first word
while( *str++ != ' ')
l1++;
i += 1;

//find position of second word
while ( i less-than y){
if ( *str == ' ')
i++;
str++;
}
p2 = str;
//find length of second word
while( *str++ != ' ')
l2++;
//end position of 2nd word
p2 = str + l2-1;

int start_pos_of_word1 = p1-s;
int end_pos_of_word2 = p2-s;

rev(s,start_pos_of_word1,end_pos_of_word2);
rev(s,start_pos_of_word1, start_pos_of_word1 + l2);
rev(s,end_pos_of_word2 - l1, end_pos_of_word2);
rev(s,start_pos_of_word1+l2, end_pos_of_word2-l1);
return s

}

0 comments:

Post a Comment