Fog Creek Software
Discussion Board

reverse a string - word by word

I think I've fgured it out :

first reverse the string character by character,
then reverse each word in the resulting string (I hope there are no hidden caveats)

void swap(char *i, char *j)
  char c = *i;
  *i = *j;
  *j = c;

void reverse(char *s)
  char *i, *j, *k;
  for(j=s; *(j+1); j++)
  for(i=s; i < j; i++, j--)
    swap(i, j);
  for(i=s, k=s-1; *i;)
      for(k++; *k && (*k != ' '); k++)
      for(j=k-1; i < j; i++, j--)
    swap(i, j);

Frederic Merizen
Sunday, April 17, 2005

hay whats is the complexcity of this approach ?

Biswajit Paul
Thursday, May 5, 2005

hey its simple
read word by word(seperating them by using the blank spaces)
put the words word in a linked list one in a node
now print the reversed linked list

Monday, May 16, 2005

well i would prefer to use recursion.

First using recursion move character by character till "\0"

at the same time with the help of a local varialble we will find the starting index of each words.

Finally, the word is printed with the index till the " " | "\0"
is reached.

Monday, May 30, 2005

*  Recent Topics

*  Fog Creek Home