字符函数库cctype

字符函数库cctype

cctype

1.c++从从语言继承了一个与字符相关的函数软件包,可以确定字符是否为大写字母,数字,标点符号。这些函数的必须在头文件cctype中定义。
如:如果ch是一个字母,则isalpha(ch)函数返回一个非0值,否则返回0。同样,如果ch是标点符号,函数ispunct(ch)将返回true。这些函数的返回类型为int,而不是bool,但通常bool转换让我们能够将它们视为bool类型。
2.使用&&和||运算符来测试字符ch是否为字母:

if((ch>='a' && ch<='z')||(ch>='A'&&ch<='Z'))

与使用isalpha()相比:

if(isalpha(ch))

isalpha是不是跟方便,通用。
例子:使用isalpha()函数来检查字符是否为字母字符,使用isdigits()来测试字符是否为数字字符,使用isspace()函数来测试字符是否为空白如:换行符,空格,制表符。使用ispuntct来测试字符是否为标点符号。

#include <iostream>
#include<cctype>
using namespace std;
int main()
{
    cout<<"Enter text for analysis,and type @"
          "to terminate input"<<endl;
    char ch;
    int whitespace=0;
    int digits=0;
    int chars=0;
    int punct=0;
    int others=0;

    cin.get(ch);
    while(ch !='@')
    {
        if(isalpha(ch))
            chars++;
        else if(isspace(ch))
            whitespace++;
        else if(isdigit(ch))
            digits++;
        else if(ispunct(ch))
            punct++;
        else
            others++;
        cin.get(ch);
    }
    cout<<chars<<"letters,"
       <<whitespace<<"whitespace,"
      <<digits<<"digits,"
     <<punct<<"punctuations,"
    <<others<<"others"<<endl;
    return 0;
}

运行:注意,空白字符计数中包括换行符。
在这里插入图片描述
3.像这样的函数还有很多,如下表所示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值