用C语言写一个程序:从键盘输入字符串,统计字符串中数字字符出现的次数并输出
时间: 2024-04-30 11:17:33 浏览: 16
下面是一个简单的 C 语言程序,可以实现从键盘输入字符串,统计字符串中数字字符出现的次数并输出:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, count = 0;
printf("请输入字符串:");
scanf("%s", str);
for (i = 0; i < strlen(str); i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
printf("字符串中数字字符出现的次数为:%d\n", count);
return 0;
}
```
程序首先声明一个字符数组 `str`,用于存储输入的字符串。然后使用 `scanf` 函数从键盘读入字符串,存储到 `str` 数组中。
接着使用 `for` 循环遍历字符串中的每个字符,如果当前字符是数字字符,则将计数器 `count` 加 1。
最后输出计数器 `count` 的值,即字符串中数字字符出现的次数。
需要注意的是,这个程序只能统计 ASCII 码表中的数字字符,如果字符串中包含其他编码的数字字符,可能无法正确统计。同时,这个程序也没有对字符串长度进行限制,如果输入的字符串过长,可能会导致程序崩溃。
相关问题
用C语言编写一个程序:键盘输入一个字符串,统计其中数字、英文字符、空格和其它字符的个数。
我可以回答这个问题。下面是用C语言编写的示例代码:
```c
#include <stdio.h>
int main() {
char str[100];
int i, digits = 0, letters = 0, spaces = 0, others = 0;
printf("请输入一串字符串:");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
digits++;
} else if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
letters++;
} else if (str[i] == ' ') {
spaces++;
} else {
others++;
}
}
printf("字符串中有 %d 个数字,%d 个英文字符,%d 个空格,%d 个其他字符。\n", digits, letters, spaces, others);
return 0;
}
```
它会读取一个字符串,并统计其中数字、英文字符、空格和其他字符的个数。
用C语言写出以下程序:输入一行字符串,统计其中大写字母、小写字母、数字和其它字符的个数。
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, upper=0, lower=0, digit=0, other=0;
printf("Enter a string: ");
fgets(str, 100, stdin);
for(i=0; str[i]!='\0'; i++) {
if(isupper(str[i]))
upper++;
else if(islower(str[i]))
lower++;
else if(isdigit(str[i]))
digit++;
else
other++;
}
printf("Uppercase letters: %d\n", upper);
printf("Lowercase letters: %d\n", lower);
printf("Digits: %d\n", digit);
printf("Other characters: %d\n", other);
return 0;
}
```
代码解释:
- `fgets()` 函数用于从标准输入(键盘)读取字符串。
- `isupper()`、`islower()` 和 `isdigit()` 函数用于判断字符是否为大写字母、小写字母或数字。
- `other` 变量用于统计其他字符的个数。它的初值为 0,每次遇到不是大写字母、小写字母和数字的字符时,就将它加 1。