C语言从键盘上输入一个字符串,要求统计并输出该字符串中各位数字、大写字母、小写字母、空格和其他字符出现的次数

#include <stdio.h>
#include <string.h>
int main()
{
    char str[100];
    int i,num=0,space=0,capital=0,lowercase=0,other=0;
    /*num数字,space空格,capital大写字母,lowercase小写字母
    ,other其他字符*/
    printf("请输入字符串");
    gets(str);
    //    for(i=0;i<strlen(str);i++)//strlen用于计算字符串长度
for(i=0;str[i]!='\0';i++)
    {
    if(str[i]>='0'&&str[i]<='9') num++;
        else if(str[i]==' ') space++;
            else if(str[i]>='A'&&str[i]<='Z') capital++;
                else if(str[i]>='a'&&str[i]<='z') lowercase++;
                    else other++;
    }

    printf("数字数量为:%d\n大写字母数量为:%d\n小写字母数量为:%d\n空格数量为%d\n其他字符数量为:%d\n",num,capital,lowercase,space,other);                
     return 0;
}

  • 11
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的C语言程序,可以实现从键盘读入一个字符串,然后统计字符串数字大写字母小写字母以及空格字符的个数。 ``` #include <stdio.h> #include <ctype.h> int main() { char str[100]; int i, digits = 0, uppercase = 0, lowercase = 0, spaces = 0; printf("请输入一个字符串:"); gets(str); for(i = 0; str[i] != '\0'; i++) { if(isdigit(str[i])) { digits++; } else if(isupper(str[i])) { uppercase++; } else if(islower(str[i])) { lowercase++; } else if(isspace(str[i])) { spaces++; } } printf("数字个数:%d\n", digits); printf("大写字母个数:%d\n", uppercase); printf("小写字母个数:%d\n", lowercase); printf("空格字符个数:%d\n", spaces); return 0; } ``` 这个程序,我们首先定义了一个字符数组 `str`,用于存储从键盘读入的字符串。然后定义了四个变量 `digits`, `uppercase`, `lowercase` 和 `spaces`,分别用于统计字符串数字大写字母小写字母以及空格字符的个数,初始值都为0。 接下来,我们使用 `gets()` 函数从键盘读入字符串,并将其存储到字符数组 `str` 。然后使用 `for` 循环遍历字符串的每个字符,对于每个字符,我们使用 `isdigit()`、`isupper()`、`islower()`、`isspace()` 函数判断其是否为数字大写字母小写字母空格字符,如果是,则对应的变量加1。 最后,输出统计结果即可。 需要注意的是,`gets()` 函数不安全,容易导致缓冲区溢出,建议使用更安全的替代函数 `fgets()`。另外,本程序没有对输入字符串的长度进行检查,如果输入的字符串长度超过了字符数组 `str` 的长度,就会导致程序异常。因此,在实际应用需要对输入字符串的长度进行检查和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值