SoFunction
Updated on 2025-04-12

Summary of five ways to invert strings in Java

Preface

In Java, there are several ways to invert strings. Here are five different methods:StringBuilderofreverse()Method, use character array, use customStringBuilderMethods, direct inversion, and using Java 8's Stream API (although this approach may not be optimal in performance).

Method 1: Use StringBuilder's reverse() method

StringBuilderThe class provides areverse()Methods, which can be used directly to invert strings. This method is simple and efficient.

public class ReverseStringWithStringBuilder {
    public static void main(String[] args) {
        String original = "Hello, World!";
        StringBuilder sb = new StringBuilder(original);
        ();
        String reversed = ();
        (reversed); // Output: "!dlroW ,olleH"    }
}

Method 2: Use character array

Inverting a string through a character array is a more primitive but also efficient way to do it. This method requires traversing the string twice (one converted to a character array, one inverted).

public class ReverseStringWithCharArray {
    public static void main(String[] args) {
        String original = "Hello, World!";
        char[] charArray = ();
        int left = 0;
        int right =  - 1;

        while (left < right) {
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;

            left++;
            right--;
        }

        String reversed = new String(charArray);
        (reversed); // Output: "!dlroW ,olleH"    }
}

Method 3: Use the custom StringBuilder method

You can define a custom onereverseMethod, it accepts aStringBuilderThe start and end index of the object and the string to be reversed.

public class ReverseStringWithCustomStringBuilderMethod {
    public static void reverse(StringBuilder sb, int left, int right) {
        while (left < right) {
            char tmp = (left);
            (left++, (right));
            (right--, tmp);
        }
    }

    public static void main(String[] args) {
        String original = "Hello, World!";
        StringBuilder sb = new StringBuilder(original);
        reverse(sb, 0, () - 1);
        String reversed = ();
        (reversed); // Output: "!dlroW ,olleH"    }
}

Method 4: Direct reversal

public class StringReversal {  
  
    public static void reverseString(char[] s) {  
        int l = 0;  
        int r =  - 1;  
        while (l < r) {  
            char temp = s[l];  
            s[l] = s[r];  
            s[r] = temp;  
            l++;  
            r--;  
        }  
    }  
  
    public static void main(String[] args) {  
        char[] str = "Hello, World!".toCharArray();  
        reverseString(str);  
        (new String(str)); // Output: "!dlroW ,olleH"    }  
}

Method 5: Use Java 8's Stream API (not recommended for performance-sensitive scenarios)

While Java 8's Stream API provides a declarative way to process data, using it to invert strings may not be the most efficient way. However, to show how it is used, we can still implement it.

import ;

public class ReverseStringWithStream {
    public static void main(String[] args) {
        String original = "Hello, World!";
        String reversed = () // Convert string to int stream                                .mapToObj(c -> (char) c) // Convert an int stream to a Character object stream                                .collect(()) // Collected into List                                .stream() // Convert List back to stream                                .reduce(new StringBuilder(), StringBuilder::append, StringBuilder::append) // Use reduce and StringBuilder to splice strings                                .reverse() // Invert strings in StringBuilder                                .toString(); // Convert StringBuilder to String
        (reversed); // Output: "!dlroW ,olleH"    }
}

Notice: While the Stream API provides an elegant way to process data, using the Stream API can result in performance degradation in scenarios where large amounts of data are processed or performance-sensitive.

Summarize

This is the end of this article about five methods of Java inverting strings. For more related contents of Java inverting strings, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!