內存操作函數 (<string.h>)
| 函數 | 功能 | 關鍵點 |
memccpy | 複製不超過 n 字節,遇指定字符停止 | 返回字符後指針,未找到返回 NULL;字符會被複製 |
memchr | 在前 n 字節中查找字符 | 找到返回指針,否則 NULL |
memicmp / memcmp | 比較前 n 字節(不區分/區分大小寫) | 返回 <0, =0, >0 |
memmove | 複製 n 字節,允許源目重疊 | 安全處理重疊,返回目標指針 |
memset | 設置前 n 字節為指定字符 | 返回目標指針 |
movmem | 同 memmove(舊名) | 非標準,建議用 memmove |
setmem | 同 memset(舊名) | 非標準,建議用 memset |
字符串操作函數
| 函數 | 功能 | 關鍵點 |
stpcpy | 複製字符串 | 返回終止符 '\0' 位置指針(非標準) |
strcat | 追加字符串到目標末尾 | 目標需有足夠空間,返回目標指針 |
strchr | 查找字符首次出現位置 | 返回指針或 NULL |
strcmp | 比較兩字符串 | 返回 <0, =0, >0 |
stricmp / strcmpi | 不區分大小寫比較 | strcmpi 為宏別名 |
strcpy | 複製字符串 | 目標需足夠空間,返回目標指針 |
strcspn | 計算不含指定字符集的前綴長度 | 返回長度 |
strdup | 複製字符串並分配內存 | 需 free() 釋放 |
strlen | 計算字符串長度 | 不含 '\0' |
strlwr | 轉小寫 | 原地修改,返回指針 |
strncat | 追加前 n 字符 | 安全版 strcat |
strncmp | 比較前 n 字符 | 安全版 strcmp |
strnicmp / strncmpi | 不區分大小寫比較前 n 字符 | strncmpi 為宏別名 |
strncpy | 複製前 n 字符 | 若源長<n,目標補 '\0';否則不加終止符 |
安全編程提示
- 避免
strcpy/strcat/sprintf:無邊界檢查,首選 strncpy/strncat/snprintf 或 C11 附錄 K strcpy_s 族。
strncpy 不保證以 '\0' 結尾,用後手動添加:dest[n-1] = '\0';。
strdup 分配堆內存,必須配對 free。
- 大小寫轉換函數(
strlwr/stricmp)屬 POSIX/Windows 擴展,跨平台項目建議自行實現或用 tolower 循環。
常用模式速查
// 安全複製
char dest[64];
strncpy(dest, src, sizeof(dest)-1);
dest[sizeof(dest)-1] = '\0';
// 安全拼接
strncat(dest, src, sizeof(dest) - strlen(dest) - 1);
// 大小寫不敏感比較 (跨平台)
int strcasecmp_custom(const char *s1, const char *s2) {
while (*s1 && *s2) {
int c1 = tolower((unsigned char)*s1++);
int c2 = tolower((unsigned char)*s2++);
if (c1 != c2) return c1 - c2;
}
return tolower((unsigned char)*s1) - tolower((unsigned char)*s2);
}