1.字符分类函数
字符分类函数是C语言标准库中用于检查给定字符是否属于特定类别的一组函数。这些函数声明在 <ctype.h>
头文件中。
函数列表及描述
这些函数的参数是 int
类型,但通常传递的是 char
类型的值。为了确保无符号字符的正确扩展,推荐使用 unsigned char
类型的值或直接传递 EOF
。
-
iscntrl(int c)
: 检查是否为控制字符(非打印字符,ASCII码在0x00至0x1F之间,以及0x7F(DEL))。 -
isspace(int c)
: 检查是否为空白字符(空格、制表符、换行符、垂直制表符、换页符和回车符)。 -
isdigit(int c)
: 检查是否为数字(0至9)。 -
isxdigit(int c)
: 检查是否为十六进制数字(0至9,a至f,A至F)。 -
islower(int c)
: 检查是否为小写字母(a至z)。 -
isupper(int c)
: 检查是否为大写字母(A至Z)。 -
isalpha(int c)
: 检查是否为字母(大写或小写)。 -
isalnum(int c)
: 检查是否为字母或数字。 -
ispunct(int c)
: 检查是否为标点符号(除空格和字母数字字符外的可打印字符)。 -
isgraph(int c)
: 检查是否为除空格外的可打印字符。 -
isprint(int c)
: 检查是否为可打印字符(包括空格)。
示例代码
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
// 测试各种字符
ch = 'A';
printf("%c is alpha? %d\n", ch, isalpha(ch));
printf("%c is upper? %d\n", ch, isupper(ch));
ch = 'a';
printf("%c is lower? %d\n", ch, islower(ch));
ch = '1';
printf("%c is digit? %d\n", ch, isdigit(ch));
ch = '@';
printf("%c is punct? %d\n", ch, ispunct(ch));
ch = ' ';
printf("Space is space? %d\n", isspace(ch));
return 0;
}
输出:
A is alpha? 1
A is upper? 1
a is lower? 1
1 is digit? 1
@ is punct? 1
Space is space? 1
在这个示例中,isalpha
, isupper
, islower
, isdigit
, ispunct
, 和 isspace
函数用于检查字符是否属于特定的类别。返回值为非零值(通常是1)表示“真”,即字符属于查询的类别;返回值为0表示“假”。
2.字符转换函数
字符转换函数是C语言标准库中提供的一组函数,用于将字符在大写和小写之间转换,以及执行其他类型的字符转换。这些函数包括tolower
、toupper
等,定义在头文件<ctype.h>
中。
2.1. tolower
函数
tolower
函数用于将大写字母转换为对应的小写字母。如果传入的字符不是大写字母,则返回该字符本身。
- 原型:
int tolower(int ch);
- 参数:
ch
- 需要转换的字符。 - 返回值:如果参数是大写字母,则返回其对应的小写字母;否则,返回参数本身。
示例
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'A';
printf("Original: %c, Lowercase: %c\n", ch, tolower(ch));
return 0;
}
2.2 toupper
函数
toupper
函数用于将小写字母转换为对应的大写字母。如果传入的字符不是小写字母,则返回该字符本身。
- 原型:
int toupper(int ch);
- 参数:
ch
- 需要转换的字符。 - 返回值:如果参数是小写字母,则返回其对应的大写字母;否则,返回参数本身。
示例
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'a';
printf("Original: %c, Uppercase: %c\n", ch, toupper(ch));
return 0;
}