Friday, February 25, 2011

C++ Code for String Reverse

Here is a code for a program which does task of reversing the input string.



void StringReverse(char* pchStringToReverse)
{
        //if string is empty or having one character no need to reverse.
if(pchStringToReverse == NULL || (pcStringToReverse +1 ) == NULL) 
{
return;
}             

char* pchPointToLast = pchStringToReverse;

while(pchPointToLast)
{
pchPointToLast++;
}

pchPointToLast--;

while(pchStringToReverse < pchPointToLast)
{
     Char chTempStorage = *pchStringToReverse;
     *pchStringToReverse++  = *pchPointToLast;
     *pchPointToLast-- = chTempStorage; 
}
}

This code is written considering the string is C style string, i.e. terminating with NULL. If your string is not terminating with null then you might be need to replace the terminating conditions of while loops.

Unit Test Cases for above function:
  1. Empty String.
  2. String with only one character.
  3. String with even number of characters.
  4. String with odd number of characters.
There is one other way of doing this - its using recursion. But using recursion you can only print the string not store the string(I am not 100% sure about this).

void DisplayReverseString( char* pchStringToReverse)
{
if(*pchStringToReverse == NULL)
{
return;
}
else
{
DisplayReverseString(++pchStringToReverse);
cout<<*(pchStringToReverse -1 );
}
}

Please share your comments if any on the code or if you have any suggestions.