char hello[] = {'h','e','l','l','o','\0'}; 或 char hello[] = "hello";(編譯器自動補 \0)。#include <iostream>
#include <cstring>
using namespace std;
int main() {
char fragment1[] = "Im a s";
char fragment2[] = "tring!";
char fragment3[20];
char finalString[20] = "";
strcpy(fragment3, fragment1); // 複製
strcat(finalString, fragment3); // 串接
strcat(finalString, fragment2); // 串接
cout << finalString; // 輸出: Im a string!
return 0;
}
| 函式 | 用途 | 注意 |
|---|---|---|
strcpy(dest, src) | 複製字串 | 需確保 dest 空間足夠 |
strcat(dest, src) | 串接字串 | dest 必須以 \0 結尾且空間足夠 |
strlen(str) | 取得長度 | 不含結束 \0 |
strcmp(s1, s2) | 比較字串 | 回傳 0 表相等 |
C 風格字串操作易導致緩衝區溢位,現代 C++ 應優先使用 std::string、std::array、std::vector 等 RAII 容器。