#include <stdio.h>
#include <ctype.h> // 核心頭文件
#include <string.h>
int main() {
char str[] = "Hello World! 123";
printf("原始: %s\n", str);
// 大寫轉小寫
for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
printf("全小寫: %s\n", str);
// 小寫轉大寫
for (int i = 0; str[i]; i++) {
str[i] = toupper(str[i]);
}
printf("全大寫: %s\n", str);
// 大小寫反轉
for (int i = 0; str[i]; i++) {
if (islower(str[i])) str[i] = toupper(str[i]);
else if (isupper(str[i])) str[i] = tolower(str[i]);
}
printf("大小寫反轉: %s\n", str);
return 0;
}
<ctype.h> 核心函數表| 函數 | 功能 | 返回值 |
|---|---|---|
isupper(c) | 判斷大寫字母 | 非0(真) / 0(假) |
islower(c) | 判斷小寫字母 | 非0 / 0 |
isalpha(c) | 判斷字母 | 非0 / 0 |
isdigit(c) | 判斷數字字符 | 非0 / 0 |
isalnum(c) | 判斷字母或數字 | 非0 / 0 |
toupper(c) | 轉大寫 | 轉換後字符 (int) |
tolower(c) | 轉小寫 | 轉換後字符 (int) |
isprint(c) | 可打印字符 | 非0 / 0 |
isspace(c) | 空白字符 (空格、\t、\n等) | 非0 / 0 |
// 大寫轉小寫:第5位置1 (或加 32)
char to_lower_ascii(char c) {
if (c >= 'A' && c <= 'Z') return c + 32; // 或 c | 0x20
return c;
}
// 小寫轉大寫:第5位清0 (或減 32)
char to_upper_ascii(char c) {
if (c >= 'a' && c <= 'z') return c - 32; // 或 c & 0xDF
return c;
}
// 大小寫反轉:第5位取反
char toggle_case_ascii(char c) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
return c ^ 0x20; // XOR 32 翻轉第6位
return c;
}
'A' = 0x41 = 0100 0001
'a' = 0x61 = 0110 0001
↑
第6位 (值32) 差異
c | 0x20 → 強制第6位為1 (轉小寫)
c & 0xDF → 強制第6位為0 (轉大寫) (0xDF = 1101 1111)
c ^ 0x20 → 翻轉第6位 (大小寫反轉)
#include <ctype.h>
#include <string.h>
// 就地轉換:全大寫
void str_toupper(char *str) {
for (; *str; str++) *str = toupper(*str);
}
// 就地轉換:全小寫
void str_tolower(char *str) {
for (; *str; str++) *str = tolower(*str);
}
// 就地轉換:大小寫反轉
void str_toggle_case(char *str) {
for (; *str; str++) {
if (islower(*str)) *str = toupper(*str);
else if (isupper(*str)) *str = tolower(*str);
}
}
// 複製並轉換:返回目標緩衝區指針
char* str_copy_toupper(char *dest, const char *src) {
char *p = dest;
while (*src) *p++ = toupper(*src++);
*p = '\0';
return dest;
}
// 忽略大小寫字符串比較
int strcasecmp(const char *s1, const char *s2) {
while (*s1 && *s2) {
int c1 = toupper(*s1++);
int c2 = toupper(*s2++);
if (c1 != c2) return c1 - c2;
}
return toupper(*s1) - toupper(*s2);
}
ctype.h 函數僅保證處理 **ASCII 字符 (0-127)** 和當前 locale 的單字節字符wchar.h 寬字符函數 (towupper, towlower) 或 ICU 庫#include <time.h>
#include <ctype.h>
void benchmark() {
const int N = 10000000;
char *buf = malloc(N);
memset(buf, 'a', N);
clock_t start = clock();
for (int i = 0; i < N; i++) buf[i] = toupper(buf[i]);
printf("toupper(): %.3f ms\n", (clock()-start)*1000.0/CLOCKS_PER_SEC);
memset(buf, 'a', N);
start = clock();
for (int i = 0; i < N; i++) buf[i] = (buf[i] >= 'a' && buf[i] <= 'z') ? buf[i] - 32 : buf[i];
printf("ASCII bitwise: %.3f ms\n", (clock()-start)*1000.0/CLOCKS_PER_SEC);
free(buf);
}
典型結果:位運算快 2-5 倍,但標準庫函數處理邊界情況更安全。
ctype.h,可讀性強、可移植、自動處理 locale