Strings: Reversal, Part 2

Dave Sinkula 0 Tallied Votes 129 Views Share

In Part 1, the code reversed the string in place. This version uses a source and a destination string.

#include <stdio.h>
 
char *mystrrev(char *dst, const char *src)
{
   const char *end = src, *start = dst;
   /*
    * Point 'end' to the end of the 'src' string.
    */
   while ( *end != '\0' )
   {
      ++end;
   }
   --end; /* skip terminating null character */
   /*
    * Copy starting the from the end of the 'src' and the beginning of 'dst'.
    */
   while ( src <= end )
   {
      *dst++ = *end--;
   }
   *dst = '\0'; /* null terminate the destination string */
   return (char*)start;
}
 
int main(void)
{
   const char text[] = "Hello world";
   char result[sizeof text];
   puts(text);
   puts(mystrrev(result, text));
   return 0;
}
 
/* my output
Hello world
dlrow olleH
*/