Solution: In this program there are 3 solutions
1) Reverse string using StringBuilder API
2) Reverse string by reading from end of the string
3) Reverse string by using Recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
public class ReverseString { public static void main(String[] args) { // Reversing string using StringBuilder reverseUsingStringBuilder(new StringBuilder("htaneers")); //Reversing string by reading from end revereString("htaneers"); //Reversing string using recursive System.out.println(reverseStringRecursively("htaneers")); } private static void reverseUsingStringBuilder(StringBuilder sb) { System.out.println(sb.reverse()); } private static void revereString(String string) { char[] ch = string.toCharArray(); for(int i=ch.length-1; i>=0;i--) System.out.print(ch[i]); System.out.println(); } private static String reverseStringRecursively(String string) { if(string.length()==1) return string; return reverseStringRecursively(string.substring(1)) + string.charAt(0); } } |
Output
1 2 3 4 5 6 7 |
sreenath sreenath sreenath |