A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://howtodoinjava.com/java/string/reverse-string-using-recursion/ below:

Reverse All Characters of a String in Java

In this Java tutorial, we will learn to reverse the characters of a string using the recursion and StringBuilder.reverse() methods. You may like to read about reversing the words in a sentence also.

1. Reverse using Recursion

To reverse all the characters of the string, we can write a recursive function that will perform the following actions –

public class ReverseString {

  public static void main(String[] args) {

    String blogName = "How To Do In Java";
    String reverseString = reverseString(blogName);

    Assertions.assertEquals("avaJ nI oD oT woH", reverseString);
  }

  public static String reverseString(String string) {
    if (string.isEmpty()) {
      return string;
    }
    return reverseString(string.substring(1)) + string.charAt(0);
  }
}
2. Reverse using StringBuilder.reverse()

We can also reverse a string easily, using a StringBuilder.reverse() method. The reverse() method causes the characters of String to be replaced by the reverse of the sequence.

String blogName = "How To Do In Java";

String reverseString = new StringBuilder(blogName).reverse().toString();

Assertions.assertEquals("avaJ nI oD oT woH", reverseString);

Happy Learning !!

Sourcecode on Github


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4