java字符串反转方法
时间: 2023-11-02 13:59:43 浏览: 97
可以使用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 中,可以使用多种方法来反转字符串。以下是几种常见的方法:
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);
```
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;
}
```
阅读全文