首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C++ string 核心查找與操作函數詳解

     編輯:關於C語言

前言

std::string 提供豐富的字串處理功能,本文聚焦 find 系列、substr、插入刪除與 C 風格轉換,並以實例說明常見陷阱。

一、字元查找:find_first_of / find_last_of

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

二、子串提取:substr

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"

三、模式查找:find

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"

五、C 風格轉換:c_str

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() 回傳指標生命週期綁定原字串,修改字串後指標失效
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved