Monday, August 6, 2012

Reversing a String in ANSI C

If you're not familiar with how strings are represented in ANSI C, you should read this first:

We shall reverse the string in situ, without using an additional string. The implementation for this function is:
/**
 * Description:
 *  Reverses the received string.
 * Parameters:
 *  string - a pointer to the string who will be reversed
 * Returns:
 *  A pointer to the reversed string.
 * Postconditions:
 *  The "original" string who is sent will be reversed.
 */
char* String_Reverse(char *string)
{
   size_t last;
   int i;
   char swap;

   if(string!=NULL)
   {
      /*Computes the location of the last character*/
      last = strlen(string)-1;
      /*Itterates through the first half of the string*/
      for(i=0; i<(last/2); i++)
      {
         /*Swaps the first character with the last and so on*/
         swap = string[i];
         string[i] = string[last-i-1];
         string[last-i-1] = swap;
      }
   } 

 return string;
}
Here's an example on how to use the function:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char* String_Reverse(char *string);

int main(void)
{
   char string[] = "The simple pleasures are the last refuge of complex men";
   printf("Original string: %s\n", string);
   String_Reverse(string);
   printf("Reversed string: %s\n", string);
   return 0;
}
/*Output:
Original string: The simple pleasures are the last refuge of complex men
Reversed string: nem xelpmoc fo egufer tsal eht era serusaelp elpmis ehT
 */

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger