练习三 字符类型及其操作第1关:提取数字字符输入字符串x,将其中的数字字符('0'到'9')取出来,再逆向输出 例如 输入abc123def45gh123 输出32154321 输入123abab45 输出54321
时间: 2024-11-30 12:20:34 浏览: 64
练习三的目标是从给定的字符串 `x` 中提取所有的数字字符,并按照相反的顺序打印出来。这个过程可以分为两个步骤:
1. **提取数字字符**:遍历字符串 `x` 的每个字符,如果该字符是数字(ASCII值在 '0' 到 '9' 之间),就将其添加到结果数组或列表中。
2. **逆向输出**:得到包含所有数字字符的新字符串后,将其反转,然后逐个输出每个字符。
下面是一个简单的 Python 示例实现:
```python
def extract_and_reverse_numbers(x):
digits = []
for char in x:
if '0' <= char <= '9':
digits.append(char)
reversed_digits = digits[::-1] # 使用切片反转数组
return ''.join(reversed_digits) # 将字符连接成字符串并返回
# 测试例子
input_str = "abc123def45gh123"
output = extract_and_reverse_numbers(input_str)
print(output) # 输出:32154321
input_str = "123abab45"
output = extract_and_reverse_numbers(input_str)
print(output)
阅读全文
相关推荐


















