The following code shows different methods of reversing a String in Java. The simplest being using the reverse() method of StringBuffer, while the other methods use char array and recursion:
public class StringReverse {<br /> public static void main(String[] args) {<br /> String s = "zyxwvutsrqponmlkjihgfedcba";<br /> System.out.println(charReverse(s));<br /> System.out.println(recursiveReverse(s , new StringBuffer()));<br /> System.out.println(recursiveReverse2(s, new StringBuffer()));<br /> System.out.println(bufferReverse(s));<br /> }<br /> <br /> public static String charReverse(String s) {<br /> char[] cArr = s.toCharArray();<br /> StringBuffer reversed = new StringBuffer();<br /> for(int i=cArr.length-1; i>=0; i--) reversed.append(cArr[i]);<br /> return reversed.toString();<br /> }<br /> <br /> public static String recursiveReverse(String s, StringBuffer t) {<br /> if(s.length() > 0) {<br /> t.append(s.substring(s.length()-1));<br /> recursiveReverse(s.substring(0, s.length()-1), t);<br /> }<br /> return t.toString();<br /> }<br /> <br /> public static String recursiveReverse2(String s, StringBuffer sb) {<br /> if (s.length() == 1){<br /> sb.append(s);<br /> }<br /> else{<br /> recursiveReverse2(s.substring(1, s.length()), sb); <br /> sb.append(s.substring(0,1));<br /> }<br /> return sb.toString();<br /> }<br /> <br /> public static String bufferReverse(String s) {<br /> StringBuffer sb = new StringBuffer(s);<br /> return sb.reverse().toString();<br /> }<br />}
No comments:
Post a Comment