java中字符串反转方法
时间: 2024-11-22 18:43:48 浏览: 35
在 Java 中,可以使用多种方法来反转字符串。以下是几种常见的方法:
1. **使用StringBuilder或StringBuffer**:
```java
String original = "Hello, World!";
StringBuilder sb = new StringBuilder(original);
String reversed = sb.reverse().toString();
// 或 StringBuffer (线程安全)
StringBuffer sf = new StringBuffer(original);
String reversedSF = sf.reverse().toString();
```
2. **使用 char 数组**:
```java
char[] chars = original.toCharArray();
int start = 0;
int end = chars.length - 1;
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
String reversedChars = new String(chars);
```
3. **递归方法**:
```java
public static String reverseString(String s) {
if (s.isEmpty()) return s;
return reverseString(s.substring(1)) + s.charAt(0);
}
String reversedRecursive = reverseString(original);
```
阅读全文