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

C語言字符串與內存操作函數大全:string.h 核心 API 速查手冊

     編輯:關於C語言

內存操作函數 (<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);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved