[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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM