#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);
按字典序(基於字元 ASCII/編碼值)比較字串 s1 和 s2 的前 n 個字元。**區分大小寫**。若在比較 n 字元前遇到任一字串結束符 \\0,則提前停止比較。
s1, s2 為待比較字串;n 為最大比較字元數。< 0:s1 小於 s2。= 0:前 n 字元相等(或均提前遇到 \\0)。> 0:s1 大於 s2。// strncmp_demo.c
#include <stdio.h>
#include <string.h>
int main(void) {
const char *s1 = "Hello, Programmers!";
const char *s2 = "Hello, programmers!"; // 差異在 'P' (80) vs 'p' (112)
int r;
// 1. 比較前 6 字元 "Hello," -> 相同
r = strncmp(s1, s2, 6);
printf("比較前 6: %d (預期 0)\n", r);
// 2. 比較前 10 字元 "Hello, Pro" vs "Hello, pro" -> 'P' vs 'p' 差異
r = strncmp(s1, s2, 10);
printf("比較前 10: %d (預期負數, 'P' < 'p')\n", r);
// 3. 比較 "abc" vs "abcdef" 前 5 字元 -> s1 結束,s1 < s2
r = strncmp("abc", "abcdef", 5);
printf("'abc' vs 'abcdef' 前5: %d (負數)\n", r);
// 4. 與 strcmp 差異:strcmp 比較到 \\0 結束;strncmp 限制長度
printf("strcmp: %d\n", strcmp(s1, s2));
printf("strncmp (len=20): %d\n", strncmp(s1, s2, 20));
return 0;
}
比較前 6: 0 (預期 0)
比較前 10: -32 (預期負數, 'P' < 'p')
'abc' vs 'abcdef' 前5: -100 (負數, '\\0' < 'd')
strcmp: -32
strncmp (len=20): -32
strncmp(str, "HTTP/", 5) == 0)。qsort 或 bsearch 的比較回調中,僅比較關鍵字前綴。n = 0:直接返回 0,不存取記憶體(安全)。char 是否有號視編譯器而定。比較非 ASCII 字元(>127)時,建議轉為 unsigned char 比較或使用 memcmp。| 函數 | 比較範圍 | 大小寫 | 停止條件 |
|---|---|---|---|
strcmp | 整個字串 | 敏感 | 遇 \\0 |
strncmp | 前 n 字元 | 敏感 | 遇 \\0 或 n 字元 |
strnicmp | 前 n 字元 | 不敏感 | 遇 \\0 或 n 字元 |
memcmp | 前 n 位元組 | 二進制 | 固定 n 位元組 |