4.3 字符集与 ASCII
char 保存一个字符,但在计算机内部,字符其实对应一个较小的整数编码。ASCII 是经典字符集之一,它给英文字母、数字、标点和控制字符分配了编码。
cpp
char letter = 'A';
std::cout << static_cast<int>(letter) << std::endl; // 65字符能进行比较,正是因为它背后有数值编码。
cpp
char ch = '7';
if (ch >= '0' && ch <= '9') {
std::cout << "数字" << std::endl;
}在 ASCII 中,'0' 到 '9' 是连续的,'A' 到 'Z' 和 'a' 到 'z' 也是连续的。
C++ 还在 <cctype> 中提供了字符判断和转换函数:
cpp
#include <cctype>
if (std::isdigit(static_cast<unsigned char>(ch))) {
std::cout << "数字" << std::endl;
}
char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));这里的类型转换看起来稍微多一点,但它能让 <cctype> 函数在各种 char 值上都保持定义良好的行为。
正在加载交互实验...
正在加载概念检查...
正在加载本节练习...