写出一段完整代码,使得输入一个字符串,分别统计其中数字、空格、字母及其他字符(除数字、字母、空格之外的)出现的次数。
时间: 2023-11-08 19:00:32 浏览: 23
当然可以,以下是代码:
```python
string = input("请输入一个字符串:")
nums = 0 # 统计数字
spaces = 0 # 统计空格
letters = 0 # 统计字母
others = 0 # 统计其他字符
for char in string:
if char.isdigit():
nums += 1
elif char.isspace():
spaces += 1
elif char.isalpha():
letters += 1
else:
others += 1
print("数字的个数是:", nums)
print("空格的个数是:", spaces)
print("字母的个数是:", letters)
print("其他字符的个数是:", others)
```
代码实现很简单,通过 for 循环逐个遍历输入的字符串中的每个字符,并通过 isdigit()、isspace() 和 isalpha() 函数来判断该字符是否为数字、空格或字母,如果是便将相应的计数器加一即可。最后,输出四种类型字符的计数结果。
相关问题
写出一段完整c程序代码,使得输入一个字符串,分别统计其中数字、空格、字母及其他字符(除数字、字母、空格之外的)出现的次数。
好的,以下是对应问题的程序代码:
```c
#include<stdio.h>
#include<string.h>
void count_char(char* str, int* num_count, int* space_count, int* alpha_count, int* other_count){
int len = strlen(str);
for(int i = 0; i < len; i++){
if(str[i] >= '0' && str[i] <= '9') (*num_count)++;
else if(str[i] == ' ') (*space_count)++;
else if((str[i] >= 'a' && str[i] <='z') || (str[i] >= 'A' && str[i] <= 'Z')) (*alpha_count)++;
else (*other_count)++;
}
}
int main(){
char str[100];
int num_count = 0, space_count = 0, alpha_count = 0, other_count = 0;
printf("请输入一个字符串:");
gets(str);
count_char(str, &num_count, &space_count, &alpha_count, &other_count);
printf("数字个数:%d\n空格个数:%d\n字母个数:%d\n其他字符个数:%d\n",
num_count, space_count, alpha_count, other_count);
return 0;
}
```
请注意,此程序仅用作演示目的。实际生产中,不建议使用 `gets()` 等不安全的输入函数。
请你写出可以输入一段英文与数字混合的句子 统计出数字与英文的个数不包括空格的c语言代码
以下是可以实现该功能的 C 语言代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int num_count = 0, char_count = 0;
printf("请输入一段英文与数字混合的句子:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
num_count++;
} else if (isalpha(str[i])) {
char_count++;
}
}
printf("数字个数:%d\n字母个数:%d\n", num_count, char_count);
return 0;
}
```
解释:
1. 首先声明了一个 `char` 类型的数组 `str`,用于存储输入的字符串;
2. 然后声明了两个变量 `num_count` 和 `char_count`,分别用于存储数字和字母的个数;
3. 使用 `fgets()` 函数读取用户输入的字符串,最多读取 100 个字符;
4. 使用 `for` 循环遍历字符串中的每个字符;
5. 使用 `isdigit()` 函数判断当前字符是否为数字,如果是,则将 `num_count` 加一;
6. 使用 `isalpha()` 函数判断当前字符是否为字母,如果是,则将 `char_count` 加一;
7. 最后输出数字和字母的个数。
需要注意的是,该代码并没有考虑输入中可能存在空格的情况。如果需要统计空格的个数,可以在循环中增加一个判断条件,判断当前字符是否为空格,然后增加一个计数器即可。