[每日一题] 156. 统计字符个数(字符检测函数、代码风格、常规解法)

1. 题目来源

链接:统计字符个数

2. 题目说明

在这里插入图片描述

3. 题目解析

方法一:字符检测函数API+常规解法

题目非常简单,做这个题是为了练习各种 C 语言字符检测函数 API 接口,真是一种 炫技 的写法,但是确实够优雅。具体各种 API 可参考官方网站和这篇大佬的博文,讲解的很清楚:C语言字符检测函数:isalnum、isalpha、isascii、iscntrl、isdigit、isgraph、islower、isspace、ispunct、isupper

参见代码如下:

#include <iostream>
#include <ctype.h>
#include <string>

using namespace std;

int main() {
	string  str;
	getline(cin, str);
	int word = 0, digit = 0, space = 0, other = 0, i = 0;
	while (str[i] != '\0') {
		if (isalpha(str[i])) ++word;
		if (isdigit(str[i])) ++digit;
		if (isspace(str[i])) ++space;
		if (ispunct(str[i])) ++other;
		++i;
	}
	cout << word << " " << digit << " " << space << " " << other << endl;
	return 0;
}

正常的 C 风格即 刷题代码风格

参见代码如下:

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    char s[10005] = {0};
    // C语言读取带空格字符串,得包含头文件 #include<cstdio>
    gets(s);
    int let = 0, num = 0, spa = 0, oth = 0;
    for (int i = 0; s[i] != 0; i++) {
        if (s[i] >= 'a' && s[i] <= 'z' ||
            s[i] >= 'A' && s[i] <= 'Z') {
            let++;    
        } else if (s[i] >= '0' && s[i] <= '9') {
            num++;
        } else if (s[i] == ' ') {
            spa++;
        } else {
            oth++;
        }
    }
    cout << let << " " << num << " " << spa << " " << oth << endl;
    return 0;
}
发布了391 篇原创文章 · 获赞 329 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/yl_puyu/article/details/105000059