This recipe shows how to reverse a string. We will explore three different approaches to implementing the solution.
Given an input string, output the reverse string. For example, for the input “life is good”, the reverse output would be “doog si efil”.
The easiest solution is to utilize the StringBuilder class provided in Java.
public class ReverseString {
private static String reverse(String input) {
final StringBuilder builder = new StringBuilder(input);
return builder.reverse().toString();
}
public static void main(String[] args) {
final String input = args[0];
System.out.println(reverse(input));
}
}
Link To: Java Source Code
The next solution demonstrates an implementation using iteration.
public class ReverseString {
private static String reverse(String input) {
String reverse = "";
for (int i = input.length() - 1; i >= 0; i--) {
reverse += input.charAt(i);
}
return reverse;
}
public static void main(String[] args) {
final String input = args[0];
System.out.println(reverse(input));
}
}
Link To: Java Source Code
The final solution demonstrates an implementation using recursion.
public class ReverseString {
private static String reverse(String input) {
if ((input == null) || input.isEmpty()) {
return input;
}
return reverse(input.substring(1)) + input.charAt(0);
}
public static void main(String[] args) {
final String input = args[0];
System.out.println(reverse(input));
}
}
Link To: Java Source Code