<string.h>)| 函式 | 功能 | 安全版本 (C11 Annex K) |
|---|---|---|
strcpy(dest, src) | 複製字串 | strcpy_s(dest, destsz, src) |
strncpy(dest, src, n) | 複製前 n 字符 | strncpy_s(dest, destsz, src, n) |
strcat(dest, src) | 拼接字串 | strcat_s(dest, destsz, src) |
strncat(dest, src, n) | 拼接前 n 字符 | strncat_s(dest, destsz, src, n) |
strlen(str) | 字串長度 (不含 \0) | - |
strcmp(s1, s2) | 比較字串 (字典序) | - |
strncmp(s1, s2, n) | 比較前 n 字符 | - |
strchr(s, c) | 查找字符首次出現 | - |
strrchr(s, c) | 查找字符最後出現 | - |
strstr(s1, s2) | 查找子串首次出現 | - |
strtok(s, delim) | 分割字串 (破壞原串、非線程安全) | strtok_s |
| 函式 | 標準 | 緩衝區保護 | 保留換行 | 適用流 |
|---|---|---|---|---|
gets(buf) | C89 (C11 移除) | 無 (極危險) | 否 | stdin |
fgets(buf, n, fp) | C89 | 有 (指定 n) | 是 | 任意 FILE* |
gets_s(buf, n) | C11 | 有 | 否 | stdin |
建議:永遠使用 fgets 或 gets_s,棄用 gets。
<stdlib.h>)double atof(const char *str); // 字串轉 double int atoi(const char *str); // 字串轉 int long atol(const char *str); // 字串轉 long long long atoll(const char *str); // 字串轉 long long (C99) // 更健壯的替代:strtod, strtol, strtoul, strtoll // 提供錯誤檢測、進制支援、末尾指標回傳
<wchar.h>)支援 Unicode (UTF-16/UTF-32 視平台),前綴 L:
wchar_t *ws = L"寬字元字串"; wprintf(L"%ls\n", ws); // %ls 輸出寬字串 wcslen(ws); // 長度 wcscpy(dest, src); // 複製 wcsncpy(dest, src, n); // 複製 n 字符 wcscat(dest, src); // 拼接 wcscmp(s1, s2); // 比較 wcschr(ws, L'中'); // 查找寬字符 wcsstr(ws, L"字串"); // 查找寬子串 fgetws(buf, n, stdin); // 安全讀入寬字串
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h> // setlocale
int main() {
setlocale(LC_ALL, ""); // 支援本地化字符
// 窄字串操作
char s1[50] = "Hello";
char s2[] = " World";
strcat(s1, s2);
printf("拼接: %s (長度: %zu)\n", s1, strlen(s1));
// 安全輸入
char buf[100];
printf("輸入一行: ");
fgets(buf, sizeof(buf), stdin);
buf[strcspn(buf, "\n")] = '\0'; // 移除換行
printf("你輸入: %s\n", buf);
// 數值轉換
char num[] = "3.14159";
double val = atof(num);
printf("atof: %.5f\n", val);
// 寬字串
wchar_t ws1[50] = L"寬字元";
wchar_t ws2[] = L"測試";
wcscat(ws1, ws2);
wprintf(L"寬字串拼接: %ls (長度: %zu)\n", ws1, wcslen(ws1));
// 寬字串輸入
wchar_t wbuf[100];
fgetws(wbuf, 100, stdin);
wprintf(L"寬字串輸入: %ls", wbuf);
return 0;
}
snprintf, strncat_s, fgetschar *p = "abc"; p[0] = 'x'; // UB,用 char arr[] = "abc";strncpy 若源長 ≥ n,**不自動加 \0**,需手動補齊strcoll, wcscoll 依賴 LC_COLLATEstrtok 非線程安全,用 strtok_r (POSIX) 或 strtok_s (C11)C 語言字串操作核心在於「手動管理緩衝區、以 \0 結尾、指標運算」。掌握標準庫函式語義、安全版本替代、寬字元支援、輸入輸出最佳實踐,能寫出健壯、可移植、無安全漏洞的字串處理代碼。