在 C++ 中,cctype
头文件提供了一组函数,用于在字符级别上进行操作。这些函数通常用于测试字符的类型或对字符进行转换。
以下是 cctype
头文件中常用的函数和其功能:
isalpha(int c)
: 检查字符是否为字母(a-z 或 A-Z)。isdigit(int c)
: 检查字符是否为数字(0-9)。isalnum(int c)
: 检查字符是否为字母或数字。islower(int c)
: 检查字符是否为小写字母。isupper(int c)
: 检查字符是否为大写字母。tolower(int c)
: 如果字符是大写字母,则将其转换为小写字母;否则返回原字符。toupper(int c)
: 如果字符是小写字母,则将其转换为大写字母;否则返回原字符。isspace(int c)
: 检查字符是否为空白字符(空格、制表符、换行符等)。
#include <iostream>
#include <cctype>
int main() {
char ch = 'A';
if (isalpha(ch)) {
std::cout << "The character is alphabetic." << std::endl;
}
if (isdigit(ch)) {
std::cout << "The character is a digit." << std::endl;
}
if (isupper(ch)) {
std::cout << "The character is uppercase." << std::endl;
} else if (islower(ch)) {
std::cout << "The character is lowercase." << std::endl;
}
// 将字符转换为小写
char lowercaseCh = std::tolower(ch);
std::cout << "Lowercase of '" << ch << "' is '" << lowercaseCh << "'" << std::endl;
char ch2 = 'a';
// 将字符转换为大写
char uppercaseCh = std::toupper(ch2);
std::cout << "Uppercase of '" << ch2 << "' is '" << uppercaseCh << "'" << std::endl;
return 0;
}