Strings: Reversal

Dave Sinkula 0 Tallied Votes 611 Views Share

This is yet another example of reversing a string. This version modifies the original, reversing the string in place.

See also Strings: Reversal, Part 2.

#include <stdio.h>

char *mystrrev(char *s)
{
   char *t = s, *start = s;
   /*
    * Point 't' to the end of the string.
    */
   while ( *t != '\0' )
   {
      ++t;
   }
   /*
    * Swap the values at the beginning (pointed to by 's') and the end
    * (pointed to by 't'); 's' and 't' meet in the middle.
    */
   for ( --t/* skip terminating null character */; s < t; ++s, --t )
   {
      /* Just your run-of-the-mill swap here. */
      char temp = *s;
      *s = *t;
      *t = temp;
   }
   return start;
}

int main(void)
{
   char text[] = "Hello world";
   puts(text);
   puts(mystrrev(text));
   return 0;
}

/* my output
Hello world
dlrow olleH
*/