java字符串反转方法
时间: 2023-11-02 10:59:43 浏览: 55
可以使用StringBuilder或StringBuffer的reverse()方法反转字符串。
示例代码:
```
String str = "hello";
StringBuilder sb = new StringBuilder(str);
String reversedStr = sb.reverse().toString();
System.out.println(reversedStr); // 输出 "olleh"
```
或者使用递归方法:
```
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
} else {
return reverseString(str.substring(1)) + str.charAt(0);
}
}
String str = "hello";
String reversedStr = reverseString(str);
System.out.println(reversedStr); // 输出 "olleh"
```
相关问题
java 字符串反转
Java中可以使用StringBuffer或StringBuilder的reverse()方法来实现字符串的反转。这两个类都提供了reverse()方法来颠倒字符串的顺序。下面是一个使用StringBuilder类的例子:
```
String str = "你好,大哥哥!";
StringBuilder builder = new StringBuilder(str);
System.out.println(builder.reverse());
```
这段代码会将字符串"你好,大哥哥!"反转成"!哥哥大,好你"并输出。
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;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)