std::string 是 C++ 處理字串的標準利器。本文按功能分類彙總 9 大類常用方法,附帶簽名與語意說明,作為開發時的快速參考。
assign / operator=string& operator=(const string& s)string& assign(const char* s)string& assign(const char* s, int n) 前 n 字符string& assign(const string& s)string& assign(int n, char c) n 個字符 cstring& assign(const string& s, int pos, int n) 子串string& assign(iterator first, iterator last) 迭代器區間append / operator+=string& operator+=(const string& s)string& append(const char* s)string& append(const char* s, int n)string& append(const string& s)string& append(const string& s, int pos, int n)string& append(int n, char c)string& append(iterator first, iterator last)compare / 運算子bool operator==(const string& s1, const string& s2) 等比較運算子全支援int compare(const string& s) const 整串比較int compare(int pos, int n, const string& s) const 子串比較int compare(int pos, int n, const string& s, int pos2, int n2) const 雙子串比較const char* 重載find / rfind / find_first/last_of/not_of| 方法族 | 方向 | 用途 | 失敗回傳 |
|---|---|---|---|
find | 左→右 | 查找字符/字串首次出現位置 | string::npos |
rfind | 右→左 | 查找最後一次出現位置 | |
find_first_of | 左→右 | 查找首個屬於指定字符集的字符 | |
find_first_not_of | 左→右 | 查找首個不屬於指定字符集的字符 | |
find_last_of / not_of | 右→左 | 反向版本 |