常用字符串函數速查表
| 函數 | 功能 | 備註 |
strcpy(dst, src) | 複製字符串 | 需確保 dst 空間足夠 |
strncpy(dst, src, n) | 複製前 n 字元 | 若 src 長度 < n,補 '\0' |
strlen(str) | 返回字符串長度 | 不含結束符 '\0' |
strcat(dst, src) | 連接字符串 | dst 必須有足夠空間 |
strncat(dst, src, n) | 連接前 n 字元 | |
strcmp(s1, s2) | 比較字符串大小 | 返回 <0, =0, >0 |
strncmp(s1, s2, n) | 比較前 n 字元 | |
strchr(str, c) | 查找字元首次出現位置 | 返回指標或 NULL |
strstr(str, substr) | 查找子字符串 | 返回指標或 NULL |
fgets(buf, size, stdin) | 安全讀取一行 | 保留 '\n',優於 gets |
atoi/atol/atof/atoll | 字符串轉數值 | 無錯誤檢查,建議用 strto* |
完整示範程式
#include
#include
#include
#include
#include
int main() {
char str1[] = "This is the first string";
char str2[] = "That is the other string";
// 複製與連接
// printf("%s", strcpy(str1, str2));
// printf("%s", strncpy(str1, str2, 20));
// printf("%zu", strlen(str1));
// printf("%s", strcat(str1, str2));
// printf("%s", strncat(str1, str2, 20));
// 比較
// printf("%d", strcmp(str1, str2));
// printf("%d", strncmp(str1, str2, 5));
// 查找
// char *p = strchr(str1, 'i');
// if (p) printf("%c", *p);
// if (strstr(str1, "the")) puts("found"); else puts("not found");
// 輸入
// char buf[40];
// fgets(buf, sizeof(buf), stdin); // 安全讀取含空格行
// printf("%s", buf);
// 數值轉換
// char val[] = "99.4";
// double d = atof(val);
// printf("%f", d);
// 寬字符操作
wchar_t ws1[] = L"This is a wide string";
wchar_t ws2[] = L"another";
// wprintf(L"%S\n", ws1); // %S 輸出寬字符串
// wcslen(ws1); wcsncpy(ws1, ws2, 5);
// wcscat(ws1, ws2); wcscmp(ws1, ws2);
// wcsncmp(ws1, ws2, 5);
// wcschr(ws1, L'w'); wcsstr(ws1, L"wide");
wchar_t input[80] = L"";
fgetws(input, sizeof(input)/sizeof(wchar_t), stdin); // 讀取寬字符行
wprintf(L"%S", input);
return 0;
}
重點提醒
- gets 已棄用:無緩衝區長度檢查,極易緩衝區溢出,必須改用
fgets。
fgets 會保留換行符 '\n',處理時需自行移除。
- 寬字符函數對應關係:
strlen → wcslen、strcpy → wcscpy、printf → wprintf、格式化字符 %s → %S(或 %ls)。
- 數值轉換建議使用
strtol、strtod 等可檢測錯誤的函數。