在 C 编程中,字符变量保存一个 ASCII 值(0 到 127 之间的整数)而不是该字符本身。
小写字母的 ASCII 值是从 97 到 122、而大写字母的 ASCII 值是从 65 到 90。
如果用户输入的字符的 ASCII 值在 97 到 122 或 65 到 90 的范围内,则该数字是一个字母。
检查字母的程序
#include <stdio.h> int main() { char c; printf("Enter a character: "); scanf("%c", &c); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) printf("%c is an alphabet.", c); else printf("%c is not an alphabet.", c); return 0; }
输出
Enter a character: * * is not an alphabet
程序中用
'a'
代替
97
,用
'z'
代替
122
代码>。类似地,使用
'A'
代替
65
,使用
'Z'
代替
90
。 >
注意: 建议我们使用 isalpha( ) 函数来检查一个字符是否是字母。
if (isalpha(c)) printf("%c is an alphabet.", c); else printf("%c is not an alphabet.", c);