编写一个能保留字符串中数字字符的小程序
时间: 2024-05-04 07:19:04 浏览: 25
以下是 Python 代码实现:
```python
string = input("请输入字符串:") # 接收用户输入的字符串
digits = '' # 初始化数字字符串
for char in string:
if char.isdigit(): # 判断字符是否为数字字符
digits += char # 如果是数字字符,则添加到数字字符串中
print("字符串中的数字字符为:", digits) # 输出数字字符串
```
在这个程序中,我们首先接收用户输入的字符串,然后初始化一个空的数字字符串。接下来,我们遍历字符串中的每个字符,判断其是否为数字字符,如果是,则将其添加到数字字符串中。最后,我们输出数字字符串。
例如,如果用户输入的字符串为 `"Hello 123 World!"`,则程序将输出 `"字符串中的数字字符为:123"`。
相关问题
用C语言编写一个能保留字符串中数字字符的小程序
以下是一个简单的示例程序,可以从字符串中保留数字字符:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100], result[100];
int i, j;
printf("输入字符串:");
fgets(str, 100, stdin);
j = 0;
for (i = 0; i < strlen(str); i++) {
if (isdigit(str[i])) {
result[j] = str[i];
j++;
}
}
result[j] = '\0';
printf("结果为:%s\n", result);
return 0;
}
```
程序从标准输入中读入一个字符串,然后从字符串中筛选出数字字符,保存到另一个字符数组中,最后输出结果。程序使用了 `isdigit()` 函数来判断字符是否是数字字符。
利用指针编写一个能保留字符串中数字字符的小程序。
好的,下面是代码实现:
```c
#include <stdio.h>
#include <ctype.h>
void keepDigits(char *str, char *result) {
int i = 0, j = 0;
while (*(str + i) != '\0') {
if (isdigit(*(str + i))) {
*(result + j) = *(str + i);
j++;
}
i++;
}
*(result + j) = '\0';
}
int main() {
char str[100], result[100];
printf("请输入一个字符串:");
fgets(str, 100, stdin);
keepDigits(str, result);
printf("保留数字后的字符串为:%s", result);
return 0;
}
```
在这个程序中,`keepDigits` 函数用于将字符串中的数字字符保存到 `result` 中,而 `main` 函数则用于从用户处读取一个字符串,并将结果输出到屏幕上。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)