A String can be converted to an Array of characters and the array is inverted looping from the end to the beginning.
StringBuilder toReturn = new StringBuilder(); char[] tab = input.toCharArray(); for( int i = tab.length-1 ; i >= 0 ; i--){ toReturn.append( tab[i] ); } return toReturn.toString();
This example creates a method called reverse that converts a String to a CharArray. It loops on all the Characters from the last one to the first one and adds it to a StringBuilder
. The output is then returned.
This method is called with 2 sample Strings. The first method reverse is called twice with the output of the first call showing that the output is the same as the input.
public class StringReverse { public static String reverse(String input){ StringBuilder sb = new StringBuilder(); char[] tab = input.toCharArray(); for( int i = tab.length-1 ; i >= 0 ; i--){ sb.append( tab[i] ); } return sb.toString(); } public static void main(String[] argv) { String test = "This is a test"; // Call reverse String output = reverse( test ); System.out.println( test + " => " + output ); // Same test calling reverse twice System.out.println( test + " => " + reverse( test ) + " => " + reverse(reverse( test )) ); // With Numbers test = "0123456789"; System.out.println( test + " => " + reverse( test ) ); } }
This is a test => tset a si sihT This is a test => tset a si sihT => This is a test 0123456789 => 9876543210