how to reverse a string in java

‮w//:sptth‬ww.lautturi.com
how to reverse a string in java

There are several ways to reverse a string in Java. Here are a few options:

  1. Using a loop: You can use a loop to iterate through the characters in the string in reverse order and build a new string by adding each character to the beginning of the result string.
class Main {
  public static void main(String[] args) {
    String str = "Hello World!";
    String reversed = reverseString(str);
    System.out.println(reversed);
  }

  public static String reverseString(String str) {
    String result = "";
    for (int i = str.length() - 1; i >= 0; i--) {
      result += str.charAt(i);
    }
    return result;
  }
}

In this example, the reverseString method takes a string as an argument and returns a new string that is the reverse of the input string. The loop starts at the last character in the string and iterates backward, adding each character to the beginning of the result string.

  1. Using the StringBuilder class: You can use the StringBuilder class and its reverse method to reverse a string. The StringBuilder class provides efficient methods for modifying strings and is often used for building strings in Java.
class Main {
  public static void main(String[] args) {
    String str = "Hello World!";
    String reversed = reverseString(str);
    System.out.println(reversed);
  }

  public static String reverseString(String str) {
    StringBuilder sb = new StringBuilder(str);
    sb.reverse();
    return sb.toString();
  }
}

In this example, the reverseString method creates a StringBuilder object with the input string, then uses the reverse method to reverse the string. Finally, the toString method is used to convert the StringBuilder object to a String.

  1. Using recursion: You can also reverse a string in Java using recursion, by writing a recursive function that divides the string into two parts and calls itself on each part until the base case is reached.
class Main {
  public static void main(String[] args) {
    String str = "Hello World!";
    String reversed = reverseString(str);
    System.out.println(reversed);
  }

  public static String reverseString(String str) {
    if (str.length() == 1) {
      return str;
    }
    return reverseString(str.substring(1)) + str.charAt(0);
  }
}

In this example, the reverseString method takes a string as an argument and returns a new string that is the reverse of the input string. The method calls itself on the substring starting at the second character, and adds the first character to the end of the result. The base case is reached when the length of the string is 1, in which case the string itself is returned.

Created Time:2017-11-01 20:48:21  Author:lautturi