在程序開發中,英文字符大小寫轉換是常見需求。利用 ASCII 碼特性:小寫字母碼值比大寫字母固定大 32(即 'a' - 'A'),即可實現互轉。
char val_lower = 'a';
char val_upper = val_lower - ('a' - 'A'); // 'a' - 32 = 'A'
printf("the lower is %c, the upper is %c\n", val_lower, val_upper);
輸出:
the lower is a, the upper is A
#define TOUPPER(c) ((c) - ('a' - 'A')) // 小寫轉大寫
#define TOLOWER(c) ((c) + ('a' - 'A')) // 大寫轉小寫
printf("the lower is %c, the upper is %c\n", val_lower, TOUPPER(val_lower));
printf("the upper is %c, the lower is %c\n", val_upper, TOLOWER(val_upper));
輸出:
the lower is a, the upper is A
the upper is A, the lower is a
標準庫 <ctype.h> 提供專業轉換函數:
int toupper(int c); // 小寫轉大寫
int tolower(int c); // 大寫轉小寫
我們的宏定義缺陷:假設字符以 ASCII 表示,若系統採用其他編碼(如 EBCDIC),宏將失效。
init value : the lower is a, the upper is A
the lower is a, the upper is A
the upper is A, the lower is a
the lower is a, the upper is A
the upper is A, the lower is a
toupper/tolower,保證跨平台兼容性