April 24, 2011

Reverse String Funcion in C/Java Code

To Reverse String is not difficult, but it's one of the most popular question for interviewing in programmer job. Simple is the best, but in this case recursive function can be a better answer and efficient solution.

First method, swap first and last character repeatedly. Almost same in C and Java programming.
public String reverseString(char[] str) {
char temp;
int i, j;
for(i=0, j=str.length-1; i<=j; i++, j--){
temp = str[i];
str[i] = str[j];
str[j] = temp;
}

return new String(str);
}


Second, a recursive function can be defined. call the function within the function with Substring of input string. In Java:

public String reverseStringByRecursion(String str) {
if(str.length() == 1)
return str;
return reverseStringByRecursion(str.substring(1))
+ str.substring(0,1);
}

For C(++):
(just print character or you need global variable.)

     void StrReverse4(char *str)
     {
         if(*str)
         {
             StrReverse4(str+1);
             putchar(*str);
         } 
     }