package co.spillikin.java.jkia; /** * The clever way to reverse a string, while taking up no * additional memory. * @author chris */ public class ReverseAString { /** * If this were a C String, an alternative would be to swap thru * the zero terminator. * However the most clever way to reverse a string without using * any additional memory is to use XOR, and this works for any * type of string. * @param args */ public static void main(String[] args) { // Test a string with an even number of characters. // char data[] = {'a', 'b', 'c', 'd'}; // Test a string with an odd number of characters. char data[] = {'a', 'b', 'c', 'd', 'e'}; // Dividing an int will of course truncate down for odd lengths. // We don't need to reverse a middle char in that case. System.out.println("Initial string " + new String(data)); int strlength = data.length; for ( int i = 0; i < strlength / 2; i++) { data[i] = (char) (data[i] ^ data[strlength - i - 1]); data[strlength - i - 1] = (char) (data[i] ^ data[strlength - i - 1]); data[i] = (char) (data[i] ^ data[strlength - i - 1]); } System.out.println("Final string " + new String(data)); } }