C++ 早期無 std::string,字串以 char[] 表示。標準庫 `
| 函數 | 功能 | 備註 |
|---|---|---|
strcat(dest, src) | 字串拼接(接在 dest 尾部) | dest 必須有足夠空間 |
strcmp(s1, s2) | 比較兩字串(區分大小寫) | 相等返回 0 |
strcmpi(s1, s2) | 比較(不區分大小寫) | 非標準,部分編譯器支援 |
strcpy(dest, src) | 複製字串含結束符 | ⚠️ 易發生緩衝區溢位 |
strstr(haystack, needle) | 尋找子字串首次出現位置 | 返回指標或 nullptr |
strlen(str) | 返回有效長度(不含 \0) | |
strupr(str) | 轉大寫 | 非標準 |
sprintf(buf, fmt, ...) | 格式化輸出到緩衝區 | 支援多型別混合 |
char buff[30];
strcpy(buff, "This is a test."); // 安全
cout << buff << endl;
char buff2[] = "A second string.";
strcpy(buff, buff2); // 覆寫 buff,安全
// ⚠️ 危險範例:緩衝區溢位
char buff[10] = "A string"; // 9 字元 + \0 = 10 bytes
strcpy(buff, "This is a test."); // 16 字元 + \0 → 超出 6 bytes!
鐵律:目標緩衝區大小 必須 ≥ 來源字串長度 + 1。生產代碼建議改用 strncpy 或 std::string。
char buff[20];
int x = 10 * 20;
sprintf(buff, "The result is: %d", x); // "The result is: 200"
int a = 20, b = 5;
sprintf(buff, "%d + %d = %d", a, b, a + b); // "20 + 5 = 25"
%d 整數、%f 浮點、%s 字串、%c 字元。sprintf 不檢查緩衝區大小,C++11 起推薦 snprintf 或 std::ostringstream。strcpy(fileName, "c:\\windows\\system\\win.ini"); // 單反斜線為跳脫字元
忘記雙反斜線是經典 Bug 來源,務必肌肉記憶。
char strings[][20] = {
"This is string 1",
"This is string 2",
"This is string 3"
};
雖可用,但現代 C++ 強烈建議:
std::vector<std::string>(動態陣列)std::array<std::string, N>(固定大小)AnsiString / STL string 類別告別手動記憶體管理,擁抱型別安全與自動資源釋放。