[STRING] Reverse

16 September, 2013 - 2 min read

Problem: Given a string of unknown length reverse it in place.

Solution: Lets take a sample string "hello". When reversed it should read as "olleh". For those who are new to C/C++, a string has null terminator at the end. This null terminator denotes the end of the string. So, when you say declare a string in C language like: char *str = "hello";

How many bytes of memory does it take to store that string? 5 (for the characters) +1 (for the null). The representation of the string in memory looks like this:

Now, the reverse string should look like as shown below: If you notice, we just need to swap the first and the last characters, the 2nd and the 2nd last, 3rd and 3rd last and so on.


int main(int argc, char* argv[])
   char str[7] = "hello"; // create an array of characters of size 7
                          // and assign the string hello to it.
                          // Last char will be '' (null terminator)
   printf("%s", str);       // this will print hello
   printf("%s", str);     // this will print olleh
   return 0;

void reverse(char * str)
   char * begin = str;
   char * end = str;

   // position the end pointer at the last character
   while(*(end+1) != NULL)

   while(begin < end) // as long as begin pointer is less than end pointer
  // swap the characters
  char temp = *begin; 
  *begin = *end;
  *end = temp;

  begin++; //increment the begin ptr
  end--;  //decrememnt the end pointer