在此代码中,我可以用诸如'a','z'等字符替换ASCII代码.
int main()
{
int ch = 0;
ch = getchar();
if (ch >= 'a' && ch <= 'z')
ch -= 32;
else if (ch >= 'A' && ch <= 'Z')
ch += 32;
else
ch = -1;
if (ch == -1) {
puts("nope");
return 0;
}
putchar(ch);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果你的意思是否有可能取代if (ch >= 'A')用if (ch >= 65)?,是的,这是可能的,但不要这样做!
实际上你应该使用字符常量而不是显式的ASCII值或其他神奇的常量,例如32在代码中,因为它使代码更具可读性和可移植性(尽管不完全可移植,因为字母字符不能在EBCDIC系统上形成连续的集合,例如,但在大小写之间有一个恒定的偏移量).此外,您应该包括<stdio.h>正确性.
这是一个改进版本:
#include <stdio.h>
int main() {
int ch;
ch = getchar();
if (ch >= 'a' && ch <= 'z') // assuming lowercase letters form a contiguous set
ch += 'A' - 'a'; // change to uppercase, assuming constant offset
else if (ch >= 'A' && ch <= 'Z') // assuming uppercase letters form a contiguous set
ch += 'a' - 'A'; // change to lowercase, assuming constant offset
else
ch = -1;
if (ch == -1) {
puts("nope");
return 0;
}
putchar(ch);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但请注意,C库具有定义的函数,<ctype.h>用于处理可移植到非ASCII平台的案例转换,并且也非常易读:
这是一个便携版本:
#include <ctype.h>
#include <stdio.h>
int main() {
int ch;
ch = getchar();
if (islower(ch))
ch = toupper(ch);
else if (isupper(ch))
ch = tolower(ch);
else
ch = -1;
if (ch == -1) {
puts("nope");
return 0;
}
putchar(ch);
return 0;
}
Run Code Online (Sandbox Code Playgroud)