Write a function strrev(char *str) to reverse the contents of a string
in-place (in case you aint't supposed to use the library function).
//------------------------------------------------------------------------------
void strreverse(char* str)
{
 char* end = str;

 while( '\0' != *end )
  ++end;

 --end;

 while( str < end )
 {
  char temp = *str;
  *str = *end;
  *end = temp;

  ++str;
  --end;
 }
}

//------------------------------------------------------------------------------

Call this function on the entire string. This will ensure that the spaces
are in their correct locations.

Then keep a char pointer to a start of the word and another pointer for the
end of the word (a space / null). Replace the end with null and call strrev
on the pointer that represents the start location. Replace the null with the
original end character. Voila.


//------------------------------------------------------------------------------

void reverse_words(char* str)
{
 strreverse(str);

 char *wstart = str, *wend, cache;

 do
 {
  wend = wstart;

  while( ' ' != *wend && '\0' != *wend )
   ++wend;

  cache = *wend;
  *wend = '\0';
  {
   strreverse(wstart);
  }
  *wend = cache;

  if ( '\0' == cache )
   break;
  else
   wstart = wend + 1;

 } while( 1 );
}

//------------------------------------------------------------------------------

Hope this helps.

Cheerios
On 6/16/07, Misty <[EMAIL PROTECTED]> wrote:
>
> Hello friends,
> i want 2 know how to write a program to reverse  strings  for instance a
> string is "hello world", i need to print it as "world hello". please post
> your answers as soon as possible.
>
> >
>


-- 
"Chaos is the rule in nature, not an exception"

http://ramaswamy.r.googlepages.com

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---

Reply via email to