Java字符串逆序的四种方法及比较

发布时间 2023-07-12 18:07:58作者: 白露~

Java中实现字符串逆序有以下几种常见的方法:

public class StringReverseExample {
    public static void main(String[] args) {
        String string = "runoob";
        String reverse = new StringBuffer(string).reverse().toString();
        System.out.println("字符串反转前:" + string);
        System.out.println("字符串反转后:" + reverse);
    }
}

输出结果为:

字符串反转前:runoob
字符串反转后:boonur

这种方法的优点是简单易用,不需要额外的空间和循环。缺点是如果字符串很长,可能会占用较多的内存和时间。

public class StringReverseExample {
    public static void main(String[] args) {
        String string = "runoob";
        String result = "";
        for (int i = string.length() - 1; i >= 0; i--) {
            result = result + string.charAt(i);
        }
        System.out.println("字符串反转前:" + string);
        System.out.println("字符串反转后:" + result);
    }
}

输出结果为:

字符串反转前:runoob
字符串反转后:boonur

这种方法的优点是不需要额外的类和对象,只需要一个String变量。缺点是每次拼接都会创建一个新的String对象,如果字符串很长,可能会造成内存浪费和性能下降。

public class StringReverseExample {
    public static void main(String[] args) {
        String string = "runoob";
        char[] chars = string.toCharArray();
        int n = chars.length - 1;
        for (int i = 0; i < chars.length / 2; i++) {
            char temp = chars[i];
            chars[i] = chars[n - i];
            chars[n - i] = temp;
        }
        String result = new String(chars);
        System.out.println("字符串反转前:" + string);
        System.out.println("字符串反转后:" + result);
    }
}

输出结果为:

字符串反转前:runoob
字符串反转后:boonur

这种方法的优点是不需要创建新的String对象,只需要一个字符数组和一个临时变量。缺点是需要额外的空间来存储字符数组,并且需要遍历数组两次。

  • 方法四:使用栈的先进后出特性。这种方法是利用栈这种数据结构,将字符串的每个字符依次压入栈中,然后再依次弹出栈顶元素,并拼接成新的字符串。例如:
import java.util.Stack;

public class StringReverseExample {
    public static void main(String[] args) {
        String string = "runoob";
        int stackSize = string.length();
        Stack<Character> theStack = new Stack<>();
        for (int i = 0; i < stackSize; i++) {
            theStack.push(string.charAt(i));
        }
        StringBuilder result = new StringBuilder();
        while (!theStack.isEmpty()) {
            char ch = theStack.pop();
            result.append(ch);
        }
        System.out.println("字符串反转前:" + string);
        System.out.println("字符串反转后:" + result.toString());
    }
}

输出结果为:

字符串反转前:runoob
字符串反转后:boonur

这种方法的优点是利用了栈的特性,不需要额外的循环和交换操作。缺点是需要引入栈这种数据结构,可能会增加代码的复杂度和内存消耗。

以上就是我为你写的关于Java字符串逆序方法的博客,希望对你有所帮助。?

1: https://www.runoob.com/java/string-reverse.html 2: https://blog.csdn.net/servermanage/article/details/102662085 3: https://www.yisu.com/zixun/691389.html