1. 程式人生 > 其它 >[C++] 字串分割 (string 型別)

[C++] 字串分割 (string 型別)

比較了網上的一些split實現方法,比較喜歡利用 string 自帶函式 find 和 substr 組合實現的方法,記錄下。

參考:C++如何做字串分割(5種方法)_聽風雨-CSDN部落格_c++分割字串

std::vector<std::string> split(std::string str, std::string pattern)
{
      std::string::size_type pos;
      std::vector<std::string> result;
      str += pattern; //擴充套件字串以方便操作  不想擴充可以看下面那個
int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(pattern, i); if (pos < size) { std::string s = str.substr(i, pos - i); result.push_back(s); i = pos + pattern.size() - 1
; // - 1 是因為 之後會for迴圈 ++i } } return result; }

參考:C++常見問題: 字串分割函式 split - dfcao - 部落格園 (cnblogs.com)

void SplitString(const std::string &s, std::vector<std::string> &v, const std::string &c)
{
      std::string::size_type pos1, pos2;
      pos2 = s.find(c);
      pos1 
= 0; while (std::string::npos != pos2) { v.push_back(s.substr(pos1, pos2 - pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if (pos1 != s.length()) v.push_back(s.substr(pos1)); }

find()函式解釋:C++ string中的find()函式 - 王陸 - 部落格園 (cnblogs.com)

substr()函式解釋:C++中string如何實現字串分割函式split()_灰貓-CSDN部落格_c++ string分割字串split

C++的string為什麼不提供split函式?:C++ 的 string 為什麼不提供 split 函式? - 知乎 (zhihu.com)