java中将字符串反转
时间: 2023-12-13 19:33:20 浏览: 127
java字符串反转
以下是两种Java中将字符串反转的方法:
1.通过字符数组实现反转:
```java
public static String reverseCharArray(String s) {
char[] array = s.toCharArray();
String reverse = "";
for (int i = array.length - 1; i >= 0; i--) {
reverse += array[i];
}
return reverse;
}
```
2.通过递归实现反转:
```javapublic static String reverseRecursive(String s) {
int length = s.length();
if (length <= 1) {
return s;
}
String left = s.substring(0, length / 2);
String right = s.substring(length / 2, length);
String afterReverse = reverseRecursive(right) + reverseRecursive(left);
return afterReverse;
}
```
阅读全文