std::string 提供豐富的字串處理功能,本文聚焦 find 系列、substr、插入刪除與 C 風格轉換,並以實例說明常見陷阱。
size_type find_first_of(char c, size_type pos = 0) const;
size_type find_last_of(char c) const;
std::string::npos(非 -1)find_first_of 可指定起始位置std::string s = "Mississippi";
std::cout << s.find_first_of('s', 0) << '\n'; // 2
std::cout << s.find_first_of('s', 4) << '\n'; // 5
std::cout << s.find_last_of('s') << '\n'; // 6
string substr(size_type pos = 0, size_type len = npos) const;
len = npos 或超出尾部時,直接取到字串末尾std::string full = "Mark Tompkin";
auto sp = full.find(' ');
std::string first = full.substr(0, sp); // "Mark"
std::string last = full.substr(sp + 1); // "Tompkin"
size_type find(const string& str, size_type pos = 0) const;
在 pos 起尋找子串 str,找不到回傳 npos。
full.find("kin"); // 9
full.find("omp", 0); // 6
full.find("omp", 7); // npos
// 插入
string& insert(size_type pos, const string& str);
// 刪除
string& erase(size_type pos = 0, size_type len = npos);
std::string s = "endfile";
s += " mark"; // "endfile mark"
s.insert(3, "-of-"); // "end-of-file mark"
std::string t = "string object type";
t.erase(7, 7); // "string type"
t.erase(3, 4); // "strtype"
const char* c_str() const noexcept;
回傳以 \0 結尾的字元陣列指標,常用於需 C 字串的 API(如 fopen、open)。
std::string fname = "input.dat";
std::ifstream fin(fname.c_str()); // C++11 可直接傳 string
結合 find_last_of 與 substr 可輕鬆分離目錄、檔名、副檔名:
std::string path = "/home/user/file.txt";
auto pos1 = path.find_last_of('/');
auto pos2 = path.find_last_of('.');
std::string dir = path.substr(0, pos1 + 1); // "/home/user/"
std::string name = path.substr(pos1 + 1, pos2 - pos1 - 1); // "file"
std::string ext = path.substr(pos2 + 1); // "txt"
!= std::string::npos,勿直接與 -1 比較insert/erase 會使迭代器失效,操作後請重新取得c_str() 回傳指標生命週期綁定原字串,修改字串後指標失效