首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C 語言實例教學:字符大小寫轉換的三種實現方式

     編輯:關於C

前言:ASCII 碼與大小寫轉換的數學關係

在程序開發中,英文字符大小寫轉換是常見需求。利用 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 等其他字符集
  • 查表實現:內部使用轉換表,包含非 ASCII 字符映射
  • 安全性:非字母字符原樣返回,無副作用

我們的宏定義缺陷:假設字符以 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

總結與建議

  1. 理解 ASCII 碼數學關係是基礎
  2. 宏定義適用於簡單、確定 ASCII 環境的快速開發
  3. 生產代碼請使用 toupper/tolower,保證跨平台兼容性
  4. 完整代碼可下載參考
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved