C++ 沿用 C 的標準字串函式庫(string.h),這些函式是日常開發的基本配備。以下依功能分類整理,並附可編譯的示範程式。
char *strcpy(char *s1, const char *s2):把 s2 複製到字串陣列 s1,回傳 s1。
char *strncpy(char *s1, const char *s2, size_t n):最多複製 s2 的 n 個字元到 s1,回傳 s1。注意:若 s2 長度不足 n,尾部會以 null 補齊;若超過 n,則不會自動加上終止符號,使用時需自行處理。
char *strcat(char *s1, const char *s2):把 s2 接在 s1 之後,s2 的第一個字元會覆寫 s1 原本的 null 終止符號,回傳 s1。
char *strncat(char *s1, const char *s2, size_t n):最多串接 s2 的 n 個字元,回傳 s1。
int strcmp(const char *s1, const char *s2):比較兩字串,s1 等於、小於或大於 s2 時分別回傳 0、負值或正值。
int strncmp(const char *s1, const char *s2, size_t n):只比較前 n 個字元,回傳規則同上。
char *strtok(char *s1, const char *s2):以 s2 所含字元作為分隔符,把 s1 切分成多個 token。首次呼叫傳入 s1,後續呼叫傳入 NULL 以繼續切割同一字串;每次回傳目前的 token 指標,沒有更多 token 時回傳 NULL。
size_t strlen(const char *s):回傳 null 終止符號之前的字元數。
// 於 Visual C++ 6.0 環境下編譯通過
#include <iostream.h>
#include <string.h>
int main()
{
char str1[50] = "Happy birthday to ", str2[] = "coffeehu";
char temp1[100], temp2[6], *temp;
char str[] = "This is a sentence with 7 tokens";
strcpy(temp1, str1);
strncpy(temp2, str1, 5);
temp2[5] = '\0';
cout << "strcpy result: " << temp1 << "\n";
cout << "strncpy result: " << temp2 << "\n";
cout << "strcat result: " << strcat(str1, str2) << "\n";
cout << "strncat result: " << strncat(str1, str2, 6) << "\n";
cout << "strcmp result: " << strcmp(temp2, "Happ") << "\n";
cout << "strncmp result: " << strncmp(str1, "Happy", 5) << "\n";
temp = strtok(str, " ");
while (temp != NULL) {
cout << temp << '\n';
temp = strtok(NULL, " ");
}
cout << "strlen result: " << strlen(str2) << "\n";
return 0;
}
範例中刻意在 strncpy 之後手動補上 temp2[5] = '\0',示範了它的終止符號陷阱。另外提醒:這一整套函式都不做邊界檢查,strcat 與 strcpy 若目標緩衝區不足就會造成溢位;在正式專案中,建議改用 strlcat、strlcpy 或 C++ 的 std::string 來避免這類風險。