题解 | #计算某字符出现次数#

计算某字符出现次数

https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1

这个题有两个坑:
①用scanf函数读取字符串的时候,需要加换行符作为结束标制
②判断不区分大小写,需要用target目标字符串去判断是数字还是字符,如果用input字符串去判断是字符串还是数字的话,就会存在错误统计的情况,如:'1' +32='Q',所以会存在bug
具体代码如下:
#include <stdio.h>
#include<string.h>
int main() {
    char input[1000],target,ch;
    int count=0,k=0;
    //读取字符串
    scanf("%[^\n]\n",input);
    //读取目标字符
    scanf("%c\n",&target);
    //统计字符串中target出现的次数
    count=strlen(input)-1;
    while(count>=0){
        ch=input[count];
        //统计数字
        if(target>='0'&&target<='9'&&ch==target){
            k++;
        }else if((target>='a'&&target<='z')||(target>='A')&&(target<='Z')){
            if((target-32)==ch||(target+32)==ch||ch==target){//统计字母
                k++;
            }
        }
        count--;
    }
    printf("%d",k);
    return 0;
}


#华为机试#
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务