Java字符串反向输出的函数
时间: 2024-12-04 21:22:22 浏览: 14
在Java中,有多种方法可以反转字符串:
1. **使用StringBuilder或StringBuffer的reverse()方法**:
```java
String originalStr = "Hello, World!";
StringBuilder sb = new StringBuilder(originalStr);
String reversedStr = sb.reverse().toString(); // 或 StringBuffer 可以替换 StringBuilder
System.out.println(reversedStr); // 输出 "!dlroW ,olleH"
```
2. **使用Character数组**:
```java
String originalStr = "Hello";
char[] charArray = originalStr.toCharArray();
int start = 0, end = charArray.length - 1;
while (start < end) {
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}
String reversedStr = new String(charArray);
System.out.println(reversedStr);
```
3. **递归方法**:
```java
public static String reverse(String str) {
if (str.isEmpty()) return str;
return reverse(str.substring(1)) + str.charAt(0);
}
String originalStr = "Java";
String reversedStr = reverse(originalStr);
System.out.println(reversedStr);
```
阅读全文