1

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

Community
  • 1
  • 1
simplyblue
  • 2,279
  • 8
  • 41
  • 67

3 Answers3

9

First Reverse the string in place

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

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1
#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--; 

}

}
1

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

BlackBear
  • 22,411
  • 10
  • 48
  • 86