C++ 字符函数库cctype

来源:互联网 发布:绿色贸易壁垒的数据 编辑:程序博客网 时间:2024/05/29 16:00

C++从C语言继承了一个与字符相关的函数软件包,可以简化诸如确定字符是否为大写字母、数字、标点符号等工作,这些函数的原型在头文件cctype(老式的风格为ctype.h)中定义的。


############################################3


使用这些函数比使用AND和OR运算符更为方便。例如:

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

与使用isaplha()相比:

if (isaplha(ch))


一些常用的函数为:

isalpha()函数来检查字符是否为字母字符;

isdigits()函数来测试字符是否为数字字符;

isspace()测试字符是否为空白,如换行符、空格和制表符;

ispunct()函数来测试字符是否为标点符号

islower()函数来判断参数是否是小写字母,若是返回true

isupper()函数来判断参数是否是大写字母,若是返回true

tolower()函数:如果参数是大写字母,则返回其小写,否则返回该参数

toupper()函数:如果参数是小写字母,则返回其大写,否则返回该参数


//using the ctype.h library//void cctypes(void){cout<<"Enter text for analysis, and type @ to terminate input.\n";char ch;int whitespace=0;int digits=0;int chars=0;int punct=0;int others=0;cin.get(ch); //get first characterwhile (ch!='@') //test for sentinel{if (isalpha(ch)) //is it an alphabetic character?chars++;else if (isspace(ch)) //is it an whitespace character?whitespace++;else if (isdigit(ch)) //is it a digit?digits++;else if (ispunct(ch)) //is it punctuation?punct++;elseothers++;cin.get(ch); //get next character}cout<<chars<<" letters, "<<whitespace<<" whitespaces, "<<digits<<" digits, "<<punct<<" punctuations, "<<others<<" others.\n";cin.get();}




0 0