将字符串使用递归和循环逆序输出
时间: 2024-05-07 21:19:36 浏览: 61
递归逆序输出字符串
5星 · 资源好评率100%
使用递归实现字符串逆序输出:
```python
def reverse_string_recursive(s):
if len(s) == 0:
return s
else:
return reverse_string_recursive(s[1:]) + s[0]
s = "Hello, world!"
print(reverse_string_recursive(s))
```
使用循环实现字符串逆序输出:
```python
def reverse_string_loop(s):
result = ""
for i in range(len(s)-1, -1, -1):
result += s[i]
return result
s = "Hello, world!"
print(reverse_string_loop(s))
```
阅读全文