Search This Blog

Friday, July 29, 2011

How to Reverse a String

Question: given a string, reverse it. You can destroy the original string or return a new string that is the reverse of the original string. For example, if input is "abcde", output will be "edcba".

Solution: this is a simple problem. We just need to traverse the input string from last character to the first character. As we traversing the input string, we add its characters to the output string. At the end of the traversal, we have an output string that is the reverse of the original. Here is the code in JavaScript:

function sReverseStr(pInputStr)
{
   if (pInputStr === null || pInputStr === undefined)
      return;

   var pResultStr = "";
   
   for (var i = pInputStr.length - 1; i > -1; i--)
   {
      pResultStr += pInputStr.charAt(i);
   }

   return pResultStr;
}

Code Explanation: the code is straight forward. Here is the breakdown:

  • First, we check for invalid input. Nothing new here.
  • Next, we allocate a new string named pResultStr.
  • The for loop goes through each character in the input one by one from the end to the beginning. Then we add each of those character to the new string.
  • When the for loop finishes, pResultStr is now the reverse of the input. We simply return it.

That's all for this post. Thanks for reading :)

1 comment:

  1. This program can be optimized more further.

    1.No need of additional string
    2. No need to traverse the entire length of the string

    All you need to do is traverse from 1st to len/2, take two pointers, one at the start of string and another at end of the string and swap characters till n/2.


    String str = "welcome to tekmarathon.wordpress.com";
    //take two pointers, one pointing to the start of String and another to the end of the string
    // while traversing the String increment starting pointer and decrement ending pointer and continue this till we reach the middle of the string by this time String will be reversed
    int i = 0;
    int j = str.length();
    String tmp;

    for(i=0; i< j/2; i++) {
    // swap first letter with the last letter in the
    String tmp = str;
    str = str[j-1];
    str[j-1] = tmp;
    // move the pointer
    j--;
    }

    ReplyDelete