开发者

c program on reversing a sentence [duplicate]

This question already has answers here: Closed 10 years开发者_如何转开发 ago.

Possible Duplicate:

Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it

For example if i give a input as "This is a string" I should get the output as "string a is This" I cant get any idea on how to do it


First Reverse the string in place

Then Reverse each word in place (words are delimited by a space)


You need to find all the words then print them in reverse order. Just remember they're separated by spaces. ;)


#include<stdio.h>
void Reverse(char *,char * );

 char str[100];

void main(){

char *start,*end,i=0;

printf("\nEnter: ");

scanf("%[^\n]s",str);        //similar to gets()

start=str;

while(*(str+i)!='\0') i++;

end=str+i-1;


Reverse(start,end);

printf("\nstr:%s",str);

end=str;

for(i=0;*(str+i)!='\0';i++){


  if(*(str+i)==' ' ){
     Reverse(start,end-1);
     start=end+1;
     end=start;
     continue;
  }
  end++;
}

Reverse(start,end-1);

printf("\nstr:%s",str);  

  }

 void Reverse(char *start,char *end){

char temp=0,i=0;

while(start<end) {

  temp=*start;

  *start=*end;

  *end=temp;

  start++;

  end--; 

}

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜