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

📁 bat365在线平台app 📅 2026-01-02 17:18:50 👤 admin 👁️ 9217 ❤️ 808
Java字符串逆序的四种方法及比较

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

方法一:使用StringBuffer或StringBuilder的reverse()方法。这是最简单和最直接的方法,只需要将String对象转换为StringBuffer或StringBuilder对象,然后调用它们的reverse()方法,就可以得到逆序的字符串。例如:

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

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

方法二:使用String的charAt()方法和拼接操作。这种方法是通过遍历字符串的每个字符,从后往前取出字符,并拼接成新的字符串。例如:

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对象,如果字符串很长,可能会造成内存浪费和性能下降。

方法三:使用String的toCharArray()方法和数组交换。这种方法是先将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 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

相关推荐