位置:首页 » 文章/教程分享 » Java反转字符串的10种方法(二)

在这篇文章中,我们会讨论10种用Java反转字符串的方法,通过10个Java程序反转字符串。例如,把字符串“javaguides” 反转为 “sediugavaj”。以下将介绍剩下的5种方法。


6. 使用堆栈

package net.javaguides.corejava.string;
import java.util.Stack;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringUsingStack {
    // Function to reverse a string in Java using a stack and character array
    public static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // create an empty stack of characters
        Stack < Character > stack = new Stack < Character > ();
        // push every character of the given string into the stack
        char[] ch = str.toCharArray();
        for (int i = 0; i < str.length(); i++)
            stack.push(ch[i]);
        // start from index 0
        int k = 0;
        // pop characters from the stack until it is empty
        while (!stack.isEmpty()) {
            // assign each popped character back to the character array
            ch[k++] = stack.pop();
        }
        // convert the character array into string and return it
        return String.copyValueOf(ch);
    }
    public static void main(String[] args) {
        String str = "javaguides";
        str = reverse(str); // string is immutable
        System.out.println("Reverse of the given string is : " + str);
    }
}
输出:
Reverse of the given string is : sediugavaj

7. 使用 Collections reverse() 方法

package net.javaguides.corejava.string;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringUsingCollectionsReverseMethod {
    // Function to reverse a string in Java using Collections.reverse()
    public static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // create an empty list of characters
        List < Character > list = new ArrayList < Character > ();
        // push every character of the given string into it
        for (char c: str.toCharArray())
            list.add(c);
        // reverse list using java.util.Collections reverse()
        Collections.reverse(list);
        // covert ArrayList into String using StringBuilder and return it
        StringBuilder builder = new StringBuilder(list.size());
        for (Character c: list)
            builder.append(c);
        return builder.toString();
    }
    public static void main(String[] args) {
        String str = "Java Guides";
        // String is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}
输出:
Reverse of the given string is : sediuG avaJ

8. 使用 Byte 数组

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringUsingByteArray {
    // Function to reverse a string in Java using byte array
    public static String reverse(String str) {
        // return if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // convert string into bytes
        byte[] bytes = str.getBytes();
        // start from the two end points l and h of the given string
        // and increment l & decrement h at each iteration of the loop
        // until two end-points intersect (l >= h)
        for (int l = 0, h = str.length() - 1; l < h; l++, h--) {
            // Swap values at l and h
            byte temp = bytes[l];
            bytes[l] = bytes[h];
            bytes[h] = temp;
        }
        // convert byte array back into the string
        return new String(bytes);
    }
    public static void main(String[] args) {
        String str = "Java Guides";
        // String is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}
输出:
Reverse of the given string is : sediuG avaJ

9. 使用 substring() 方法

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class UsingSubStringFunction {
    // Function to reverse a string in Java using recursion
    private static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // last character + recurse for remaining string
        return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
    }
    public static void main(String[] args) {
        String str = "javaguides";
        // string is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}
输出:
Reverse of the given string is : sediugavaj

10. 使用递归

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class UsingRecursion {
    static int i = 0;
    // Recursive function to reverse a string in Java using static variable
    private static void reverse(char[] str, int k) {
        // if we have reached the end of the string
        if (k == str.length)
            return;
        // recurse for next character
        reverse(str, k + 1);
        if (i <= k) {
            char temp = str[k];
            str[k] = str[i];
            str[i++] = temp;
        }
    }
    public static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // convert string into a character array
        char[] A = str.toCharArray();
        // reverse character array
        reverse(A, 0);
        // convert character array into the string
        return String.copyValueOf(A);
    }
    public static void main(String[] args) {
        String str = "Java Guides";
        // string is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}
输出:
Reverse of the given string is : sediuG avaJ