ctype.h存放了与字符处理相关的函数。ctype.h中的函数通常作为宏(macro)来实现。这些C预处理器宏的作用很像函数,但是两者有一些重要的区别。
示例
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LIMIT 81
void ToUpper(char *);
int PunctCount(const char *);
//argc: 参数个数 argv[]: 参数数组
int main(int argc, char *argv[])
{
char line[LIMIT];
char * find;
puts("Please enter a line:");
fgets(line, LIMIT, stdin);
find = strchr(line, '\n');//查找换行符
if (find)//如果地址不是NULL
*find = '\0';//替换为空字符(空字符的编码为0)
ToUpper(line);
puts(line);
printf("That line has %d punctuation characters.\n", PunctCount(line));
system("pause");
return 0;
}
// 字符串转大写
void ToUpper(char * str)
{
while (*str)
{
//ANSI C之前的做法需要先判断是否为小写
//if (islower(*str))
//*str = toupper(*str);
*str = toupper(*str);
str++;
}
}
// 统计标点符号个数
int PunctCount(const char * str)
{
int ct = 0;
while (*str)
{
//是否为标点符号
if (ispunct(*str))
ct++;
str++;
}
return ct;
}
运行测试