JAVA编写一个函数reverse_string(String s)将s进行翻转,请分别使用递归和迭代两种方法,不得使用String类现有的方法
时间: 2024-04-29 22:26:28 浏览: 26
好的,我可以回答您的问题。以下是分别使用递归和迭代两种方法来翻转字符串的JAVA函数:
1. 使用递归方法翻转字符串
```java
public static String reverseStringRecursive(String str) {
if ((str == null) || (str.length() <= 1)) {
return str;
}
return reverseStringRecursive(str.substring(1)) + str.charAt(0);
}
```
在此递归函数中,我们首先检查字符串是否为空或长度为1,如果是,则返回原始字符串,否则我们先将字符串除第一个字符外的其余部分作为新字符串传递给递归函数,并添加原始字符串的第一个字符。该过程一直进行到字符串的最后一个字符被添加,然后返回整个反转字符串。
2. 使用迭代方法翻转字符串
```java
public static String reverseStringIterative(String str) {
if ((str == null) || (str.length() <= 1)) {
return str;
}
StringBuilder sb = new StringBuilder(str.length());
for (int i = str.length() - 1; i >= 0; i--)
sb.append(str.charAt(i));
return sb.toString();
}
```
这个函数在一个循环中遍历字符串的每个字符,并向 StringBuilder 对象中添加它们,以反转字符串。最后,我们将 StringBuilder 对象转换为字符串并返回。
希望我的回答能够帮助到您!
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)