Friday, September 15, 2023

 Reverse a String in Java


There are many ways to reverse a String in Java:


1. With the for-loop and reverse iteration:

public String reverse(String str) {
String reverse = "";

// iterate in reverse order
for (int i = str.length() - 1; i >= 0; i--) {
reverse += str.charAt(i);
}

return reverse;
}

2. Using StringBuilder/StringBuffer to reverse the String:

public String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}


3. Using recursion:

public String reverseString(String str) {
if (str.isEmpty()) { // BASE CASE
return str;
} else {
return reverseString(str.substring(1)) + str.charAt(0);
}

When working with recursion, it is best to use pen and paper or whiteboard and draw the each step, to better track the values that are being passed as arguments in each turn to the recursive method.


Here is one good illustration of what is happening in each turn:



Source: https://www.java67.com/2012/12/how-to-reverse-string-in-java-stringbuffer-stringbuilder.html






No comments:

Post a Comment