实验8-2-6 分类统计各类字符个数 (15 分)

本题要求实现一个函数,统计给定字符串中的大写字母、小写字母、空格、数字以及其它字符各有多少。

函数接口定义:

void StringCount( char *s );

其中 char *s 是用户传入的字符串。函数StringCount须在一行内按照

大写字母个数 小写字母个数 空格个数 数字个数 其它字符个数

的格式输出。

裁判测试程序样例:

#include <stdio.h>
#define MAXS 15

void StringCount( char *s );
void ReadString( char *s ); /* 由裁判实现,略去不表 */

int main()
{
    char s[MAXS];

    ReadString(s);
    StringCount(s);

    return 0;
}

/* Your function will be put here */

输入样例:

aZ&*?
093 Az

输出样例:

2 2 1 3 4

结尾无空行

void StringCount( char *s ) {
    int length = 0;
    while(*(s+length) != '\0'){
        length++;
    }
    int i;
    int cntBig=0, cntSmall=0, cntSpace=0, cntDigital=0, cntOther=0;
    for(i=0; i<length; i++) {
        if(*(s+i)>='A' && *(s+i)<='Z') {cntBig++;}
        else if(*(s+i)>='a' && *(s+i)<='z') {cntSmall++;}
        else if(*(s+i) == ' ') {cntSpace++;}
        else if(*(s+i)>='0' && *(s+i)<='9') {cntDigital++;}
        else cntOther++;
    }
    printf("%d %d %d %d %d", cntBig, cntSmall, cntSpace, cntDigital, cntOther);
}

//优化: 可以省去计算长度的循环, 直接在改成for(i=0; *(s+i)!='\0'; i++) 然后在里面进行判断
//或者用while循环, 条件是 *p++, 当遍历到字符串尾的时候, *p='\0'=0 ,循环条件便为假了
//可以用isupper, islower, isblank, isdigit,来作为if的判断条件
//大写字母个数 小写字母个数 空格个数 数字个数 其它字符个数
//优化后的代码:
 

#include<ctype.h>
void StringCount( char *s ) {
    char *temp;
    temp = s;
    int cntBig=0, cntSmall=0, cntSpace=0, cntDigital=0, cntOther=0;
    while(*temp) { //不会改变s本身的值
        if(isupper(*temp)) {cntBig++;}
        else if(islower(*temp)) {cntSmall++;}
        else if(isblank(*temp)) {cntSpace++;} 
        else if(isdigit(*temp)) {cntDigital++;} 
        else cntOther++;
        temp++; //纠正: 不可以在while循环中使用*temp++条件, 若使用, temp[0]则没被判断到
    }
    printf("%d %d %d %d %d", cntBig, cntSmall, cntSpace, cntDigital, cntOther);
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值