Sunday, 11 March 2018

Write a program to reverse a string using recursive method


The below example is to reverse string in java using recursive method.



package com.javadevelopersguide.www;
/**
 *
 * This Program will help you to reverse the string using recursive manner.
 *
 * @author manojkumar.bardhan
 *
 */
public class ReverseStringRecursive {
String resultString = "";
public static void main(String[] args) {
ReverseStringRecursive rec = new ReverseStringRecursive();
String inputString = "javadevelopersguide";
System.out.println("Input String::" + inputString);
String stringRev = rec.callReverse(inputString);
System.out.println("New Result String::" + stringRev);
}
private String callReverse(final String str) {
if (str.length() == 1) {
return str;
} else {
resultString += str.charAt(str.length() - 1)
+ callReverse(str.substring(0, str.length() - 1));
return resultString;
}
}
}