java如何使字符串反转
时间: 2023-10-18 08:08:20 浏览: 89
使用几种常见的方法实现字符串反转
Java中可以使用StringBuilder类或者CharArray来实现字符串反转。
1. 使用StringBuilder类:
```java
String str = "Hello World";
StringBuilder sb = new StringBuilder(str);
String reverseStr = sb.reverse().toString();
System.out.println(reverseStr);
```
2. 使用CharArray:
```java
String str = "Hello World";
char[] charArray = str.toCharArray();
int length = charArray.length;
for (int i = 0; i < length / 2; i++) {
char temp = charArray[i];
charArray[i] = charArray[length - 1 - i];
charArray[length - 1 - i] = temp;
}
String reverseStr = new String(charArray);
System.out.println(reverseStr);
```
阅读全文