標準庫函數 strcmp 區分大小寫比較字符串(基於 ASCII 碼值)。在某些業務場景下(如用戶名、不區分大小寫的關鍵字匹配),需要實現忽略字母大小寫的字符串比較:即 "Hello" 和 "hello" 應判定為相等。
gets 讀取(注意:gets 不安全,現代代碼建議用 fgets)。<:第一個串小於第二個>:第一個串大於第二個=:兩串相等(忽略大小寫)strcasecmp (POSIX) / _stricmp (Windows)最簡單、最高效的方式是直接調用平台提供的不區分大小寫比較函數。
#include <stdio.h>
#include <string.h>
#include <strings.h> // strcasecmp 在 Linux/Unix 下需要此頭文件
int main() {
char s1[81], s2[81];
fgets(s1, sizeof(s1), stdin);
fgets(s2, sizeof(s2), stdin);
// 移除 fgets 讀取的換行符
s1[strcspn(s1, "\n")] = '\0';
s2[strcspn(s2, "\n")] = '\0';
int cmp = strcasecmp(s1, s2); // Windows 用 _stricmp
if (cmp < 0) printf("<");
else if (cmp > 0) printf(">");
else printf("=");
return 0;
}
逐字符將大寫字母轉為小寫(或統一轉大寫)後比較,直到遇到不同字符或字符串結束。
#include <stdio.h>
#include <ctype.h> // toupper / tolower
int my_stricmp(const char *s1, const char *s2) {
while (*s1 && *s2) {
char c1 = tolower((unsigned char)*s1);
char c2 = tolower((unsigned char)*s2);
if (c1 != c2) return c1 - c2;
s1++; s2++;
}
// 處理長度不同但前綴相同的情況
return tolower((unsigned char)*s1) - tolower((unsigned char)*s2);
}
int main() {
char s1[81], s2[81];
fgets(s1, sizeof(s1), stdin);
fgets(s2, sizeof(s2), stdin);
s1[strcspn(s1, "\n")] = '\0';
s2[strcspn(s2, "\n")] = '\0';
int res = my_stricmp(s1, s2);
if (res < 0) putchar('<');
else if (res > 0) putchar('>');
else putchar('=');
return 0;
}
gets,改用 fgets 並手動去除換行符。tolower/toupper 時需轉為 unsigned char 避免負值導致未定義行為。