建立與賦值
#include
using namespace std;
string s1("chenyufeng", 3); // "che":複製前 n 字元
string s2("chenyufeng", 2, 3); // "eny":從 pos 複製 n 字元
string s3 = "Robert"; // 直接賦值
交換、追加、插入
swap(s1, s2); // 交換內容
s1 += s2; // 追加字串
s1.append("_OK"); // 追加字面值
s1.insert(3, "__"); // pos 3 插入 "__"
刪除與替換
s1.erase(); // 清空(同 clear())
s1.clear(); // 清空
s1.replace(3, 2, "66"); // pos 3 起 2 字元替換為 "66"
比較與長度
// 運算符比較(字典序/ASCII)
if (s1 == s2) ...
if (s1 < s2) ...
size_t len1 = s1.size(); // 不含結尾 \0
size_t len2 = s1.length(); // 同 size()
bool empty = s1.empty(); // 判空
輸入輸出與容量
cin >> s1; // 以空白分隔讀取
getline(cin, s1); // 讀取整行(含空白)
cout << s1.max_size(); // 理論最大容量
元素存取與修改
char c = s1[3]; // 無邊界檢查
char c = s1.at(3); // 有邊界檢查(拋 out_of_range)
s1[3] = 'X'; // 修改字元
比較、子串、查找
int cmp = s1.compare("chen"); // 0 相等,>0 大於,<0 小於
string sub = s1.substr(4, 3); // 從 4 起取 3 字元
string sub2 = s1.substr(4); // 從 4 起至末尾
size_t pos = s1.find('n'); // 首次出現位置
size_t pos2 = s1.find_first_of('e'); // 首次出現 'e'
size_t pos3 = s1.find_last_of('e'); // 最後出現 'e'
關鍵提醒