Reverse a String in Java
This is one of the popular java interview questions asked by many interviewers. The idea of this post is to provide some of the popular ways to reverse a String.
Below are some of the popular ways to reverse a string in java. Note that there is no reverse method in String, otherwise we could have avoided all these workaround methods.
Reverse String using StringBuilder or StringBuffer
Easiest solution to this is by using StringBuffer and StringBuilder classes which provides reverse method, so we can use that to reverse a string.
1 2 3 4 |
String input = "java"; StringBuilder sb = new StringBuilder(input); String result = sb.reverse().toString(); System.out.println(result); //prints 'avaj' |
Reverse String using Char Array
Another ways is by using a char array and then traverse it in reverse direction and populate a second char array from it. Then use the second char array to create the string that will be reversed of the first one.
Example
1 2 3 4 5 6 7 8 9 |
String input = "java"; char [] ca = input.toCharArray(); char [] result = new char [ca.length]; int len = ca.length; for(char c : ca) { result[len-1] = c; len--; } System.out.println(new String(result)); |
Reverse String using Byte Array
This is Same char array, but using byte array. Code is shown below.
Example
1 2 3 4 5 6 7 8 9 |
String input = "java"; byte [] ba = input.getBytes(); byte [] result = new byte [ba.length]; int len = ba.length; for(byte b : ba) { result[len-1] = b; len--; } System.out.println(new String(result)); |
Reverse String Word by Word
Sometimes we want words to be reversed in a sentence, not char by char. Below is a sample code showing how to do it using String split function and StringBuilder.
1 2 3 4 5 6 7 |
String inputLine = "old is gold"; String[] words = inputLine.split(" "); StringBuilder sb = new StringBuilder(); for (int i = words.length-1; i >= 0; i--) { sb.append(words[i]).append(' '); } System.out.println("Reversed sentence = '" + sb.toString().trim()+"'"); |