Cctype字符函数库
是什么
Cctype字符函数库是C++标准库中的一部分,用于堆字符进行分类和转换操作。他提供了一些函数,可以判断字符的类型,例如是否为字母、数字、空格等,还可以进行大小写转换。
常用函数
- isalpha©:判断字符c是否为字母,如果是字母则返回true,否则返回false。
- isdigit©:判断字符c是否为数字,如果是数字则返回true,否则返回false。
- isspace©:判断字符c是否为空格,包括空格、制表符、换行符等,如果是空格则返回true,否则返回false。
- islower©:判断字符c是否为小写字母,如果是小写字母则返回true,否则返回false。
- isupper©:判断字符c是否为大写字母,如果是大写字母则返回true,否则返回false。
- tolower©:将字符c转换为小写字母,如果c是大写字母则返回相应的小写字母,否则返回原字符c。
- toupper©:将字符c转换为大写字母,如果c是小写字母则返回相应的大写字母,否则返回原字符c。
怎么用
以下是一个简单的示例,演示如何使用 cctype 头文件中的函数:
#include <iostream>
#include <cctype>
int main() {
char ch = 'A';
if (isalpha(ch)) {
std::cout << ch << " is an alphabet." << std::endl;
}
else {
std::cout << ch << " is not an alphabet." << std::endl;
}
ch = '5';
if (isdigit(ch)) {
std::cout << ch << " is a digit." << std::endl;
}
else {
std::cout << ch << " is not a digit." << std::endl;
}
ch = ' ';
if (isspace(ch)) {
std::cout << ch << " is a whitespace character." << std::endl;
}
else {
std::cout << ch << " is not a whitespace character." << std::endl;
}
ch = 'b';
if (isupper(ch)) {
std::cout << ch << " is an uppercase letter." << std::endl;
}
else {
std::cout << ch << " is not an uppercase letter." << std::endl;
}
ch = 'C';
if (islower(ch)) {
std::cout << ch << " is a lowercase letter." << std::endl;
}
else {
std::cout << ch << " is not a lowercase letter." << std::endl;
}
ch = 'a';
std::cout << "Uppercase of " << ch << " is " << static_cast<char>(toupper(ch)) << std::endl;
ch = 'D';
std::cout << "Lowercase of " << ch << " is " << static_cast<char>(tolower(ch)) << std::endl;
return 0;
}
运行上述代码,将会输出:
A is an alphabet.
5 is not a digit.
is a whitespace character.
b is not an uppercase letter.
C is a lowercase letter.
Uppercase of a is A
Lowercase of D is d
代码中使用了 isalpha
、isdigit
、isspace
、isupper
、islower
、toupper
和 tolower
函数来对字符进行处理和判断,并通过条件语句进行相应的输出。注意,toupper
和 tolower
函数返回的是转换后的字符的 ASCII 值,需要使用 static_cast<char>
进行转换以得到字符。