字符串分类统计C++

题目描述

输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。

输入

一行字符

输出

统计值

样例输入

aklsjflj123 sadf918u324 asdf91u32oasdf/.';123

样例输出

23 16 2 4

使用库函数<ctype.h> 

int isalnum(int c)
该函数检查传递的字符是否是字母数字。

int isalpha(int c)
该函数是否传递的字符是字母。

int iscntrl(int c)
该函数是否传递的字符是控制字符。

int isdigit(int c)
该函数是否传递的字符是十进制数字。

int isgraph(int c)
该函数是否传递的字符的图形表示,使用的语言环境。

int islower(int c)
该函数检查传递的字符是否是小写字母。

int isprint(int c)
该函数检查传递的字符是否是可打印的。

int ispunct(int c)
该函数检查传递的字符是否是标点符号。

int isspace(int c)
该函数检查传递的字符是否是空白(空格)。

int isupper(int c)
该函数检查传递的字符是否是大写字母。

int isxdigit(int c)
该函数检查传递的字符是否是十六进制数字。
该库还包含两个转换函数,也接受并返回一个“整数”
#include<iostream>
#include<algorithm>
#include<queue>
#include<stdio.h>
#include<cstring>
#include<string>
#include<ctype.h>
using namespace std;

int main() {
    int letter=0,number=0,black=0,other=0;
    char c;
    while((c=getchar())!='\n'){
        if(isalpha(c))letter++;
        else if(isdigit(c))number++;
        else if(c==' ')black++;
        else other++;
    }
        cout<<letter<<" "<<number<<" "<<black<<" "<<other;
    return 0;
}

不用库函数,利用ASCII码

#include<iostream>
#include<algorithm>
#include<queue>
#include<stdio.h>
#include<cstring>
#include<string>
#include<ctype.h>
using namespace std;

int main() {
    int letter=0,number=0,black=0,other=0;
    char c;
    while((c=getchar())!='\n'){
        if(c>='A'&&c<='Z'||c>='a'&&c<='z')letter++;
        else if(c>='0'&&c<='9')number++;
        else if(c==' ')black++;
        else other++;
    }
        cout<<letter<<" "<<number<<" "<<black<<" "<<other;
    return 0;
}

注意:getchar可以接收键盘的输入除回车以外,每次获取一个

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值