Common Methods to Reverse a String in Java

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

How do we reverse a string In Java?

回答:

In Java, there are several ways to reverse a string. Here are a few common methods:

Method 1: Using StringBuilder

The StringBuilder class has a built-in method called reverse() that can be used to reverse a string easily.

public class ReverseString {
    public static void main(String[] args) {
        String original = "Hello, World!";
        String reversed = new StringBuilder(original).reverse().toString();
        System.out.println(reversed); // Output: !dlroW ,olleH
    }
}

Method 2: Using a Loop

You can also reverse a string by iterating through it in reverse order and building a new string.

public class ReverseString {
    public static void main(String[] args) {
        String original = "Hello, World!";
        String reversed = "";
        
        for (int i = original.length() - 1; i >= 0; i--) {
            reversed += original.charAt(i);
        }
        
        System.out.println(reversed); // Output: !dlroW ,olleH
    }
}

Method 3: Using a Character Array

You can convert the string to a character array, reverse the array, and then create a new string from the reversed array.

public class ReverseString {
    public static void main(String[] args) {
        String original = "Hello, World!";
        char[] charArray = original.toCharArray();
        String reversed = "";
        
        for (int i = charArray.length - 1; i >= 0; i--) {
            reversed += charArray[i];
        }
        
        System.out.println(reversed); // Output: !dlroW ,olleH
    }
}

Method 4: Using Recursion

You can also reverse a string using a recursive method.

public class ReverseString {
    public static void main(String[] args) {
        String original = "Hello, World!";
        String reversed = reverse(original);
        System.out.println(reversed); // Output: !dlroW ,olleH
    }

    public static String reverse(String str) {
        if (str.isEmpty()) {
            return str;
        }
        return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
    }
}

Summary

These are some of the common methods to reverse a string in Java. The StringBuilder method is generally the most efficient and straightforward way to achieve this.