C++ 字符处理 cctype
C++ 字符处理 cctype
C++ 字符处理 cctype
<cctype>(C 风格为 <ctype.h>)提供字符分类和转换函数。
一、字符分类函数
所有分类函数返回 int,非零为真,零为假。
| 函数 | 说明 |
|---|---|
isalpha(c) | 是否为字母 (a-z, A-Z) |
isdigit(c) | 是否为数字 (0-9) |
isalnum(c) | 是否为字母或数字 |
islower(c) | 是否为小写字母 |
isupper(c) | 是否为大写字母 |
isspace(c) | 是否为空白字符(空格、\t、\n、\r 等) |
isblank(c) | 是否为空白(空格、\t) |
ispunct(c) | 是否为标点符号 |
isprint(c) | 是否为可打印字符 |
isgraph(c) | 是否为可打印字符(不含空格) |
iscntrl(c) | 是否为控制字符 |
isxdigit(c) | 是否为十六进制数字 (0-9, a-f, A-F) |
二、字符转换函数
| 函数 | 说明 |
|---|---|
tolower(c) | 转小写 |
toupper(c) | 转大写 |
三、基本用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char c = 'A';
// 分类
cout << isalpha(c) << endl; // 非0(真)
cout << isupper(c) << endl; // 非0(真)
cout << isdigit(c) << endl; // 0(假)
// 转换
cout << (char)tolower(c) << endl; // 输出: a
return 0;
}
四、实用示例
统计字符类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main() {
string s = "Hello World 123!";
int letters = 0, digits = 0, spaces = 0;
for (char c : s) {
if (isalpha(c)) letters++;
else if (isdigit(c)) digits++;
else if (isspace(c)) spaces++;
}
cout << "字母: " << letters << endl; // 输出: 10
cout << "数字: " << digits << endl; // 输出: 3
cout << "空格: " << spaces << endl; // 输出: 2
return 0;
}
字符串大小写转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
// 转小写
for (char& c : s) c = tolower(c);
cout << s << endl; // 输出: hello world
// 转大写
for (char& c : s) c = toupper(c);
cout << s << endl; // 输出: HELLO WORLD
return 0;
}
判断并读取单词
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char c;
while (cin.get(c)) {
if (isalpha(c)) {
cout << c;
} else if (isspace(c)) {
cout << endl;
}
}
return 0;
}
五、注意事项
- 参数类型为
int,传入char会自动提升 - 传入
EOF或非法值时行为未定义 - 转换函数返回
int,需显式转为char
本文由作者按照 CC BY 4.0 进行授权