主题
ctype.h 字符函数
字符分类函数
<ctype.h> 提供一组函数判断字符的类别——是字母、数字、空白等。它们接受一个 int 参数(字符的 ASCII 值),返回非零表示"是",零表示"否":
c
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char chars[] = {'A', '5', ' ', 'z', '?'};
int n = sizeof chars;
for (int i = 0; i < n; i++) {
char c = chars[i];
printf("'%c': alpha=%d digit=%d alnum=%d space=%d\n",
c, !!isalpha((unsigned char)c), !!isdigit((unsigned char)c),
!!isalnum((unsigned char)c), !!isspace((unsigned char)c));
}
return 0;
}输出:
text
'A': alpha=1 digit=0 alnum=1 space=0
'5': alpha=0 digit=1 alnum=1 space=0
' ': alpha=0 digit=0 alnum=0 space=1
'z': alpha=1 digit=0 alnum=1 space=0
'?': alpha=0 digit=0 alnum=0 space=0isalpha:字母(a-z, A-Z)isdigit:十进制数字(0-9)isalnum:字母或数字isspace:空白(空格、制表符、换行等)
注:这些函数的参数必须是
unsigned char范围的值(0~255)或EOF。直接传一个char如果是负值(非 ASCII 字符)可能导致未定义行为。安全做法是传(unsigned char)c。
大小写转换
toupper 把小写字母转大写,tolower 把大写转小写。如果传入的字符不是字母,原样返回:
c
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char s[] = "Hello, World 123";
for (int i = 0; s[i] != '\0'; i++) {
putchar(toupper((unsigned char)s[i]));
}
putchar('\n');
for (int i = 0; s[i] != '\0'; i++) {
putchar(tolower((unsigned char)s[i]));
}
putchar('\n');
return 0;
}输出:
text
HELLO, WORLD 123
hello, world 123toupper('a') 得 'A',tolower('A') 得 'a',非字母字符(逗号、空格、数字)原样返回。注意 putchar 输出单个字符。
判断大小写
isupper 判断是否大写字母,islower 判断是否小写:
c
#include <stdio.h>
#include <ctype.h>
int main(void)
{
const char *s = "Ab3";
for (int i = 0; s[i] != '\0'; i++) {
char c = s[i];
printf("'%c': upper=%d lower=%d\n", c,
!!isupper((unsigned char)c), !!islower((unsigned char)c));
}
return 0;
}输出:
text
'A': upper=1 lower=0
'b': upper=0 lower=1
'3': upper=0 lower=0'A' 是大写,'b' 是小写,'3' 都不是。
统计字符类别
结合分类函数可以方便地统计字符串中各类字符的数量:
c
#include <stdio.h>
#include <ctype.h>
int main(void)
{
const char *text = "Hello World 2025!";
int letters = 0, digits = 0, spaces = 0, others = 0;
for (int i = 0; text[i] != '\0'; i++) {
unsigned char c = text[i];
if (isalpha(c))
letters++;
else if (isdigit(c))
digits++;
else if (isspace(c))
spaces++;
else
others++;
}
printf("text: \"%s\"\n", text);
printf("letters=%d digits=%d spaces=%d others=%d\n",
letters, digits, spaces, others);
return 0;
}输出:
text
text: "Hello World 2025!"
letters=10 digits=4 spaces=2 others=1"Hello World 2025!" 中有 10 个字母、4 个数字、2 个空格、1 个其他字符(!)。if-else if 链保证每个字符只被计入一个类别。
常用 ctype 函数速查
| 函数 | 判断内容 |
|---|---|
isalpha(c) | 字母(a-z, A-Z) |
isdigit(c) | 数字(0-9) |
isalnum(c) | 字母或数字 |
isspace(c) | 空白(空格、\t、\n 等) |
isupper(c) | 大写字母 |
islower(c) | 小写字母 |
isprint(c) | 可打印字符 |
toupper(c) | 转大写 |
tolower(c) | 转小写 |
要点
<ctype.h>的分类函数返回非零为真、0 为假;转换函数对非目标字符原样返回。- 传参时用
(unsigned char)c转换,避免负值char导致未定义行为。 toupper/tolower不改变非字母字符,原样返回。- 分类函数适合用于统计、过滤、词法分析等场景。
isprint判断可打印字符(含空格),isspace判断空白字符。