C++中實現字符串分割split

C++默認沒有提供字符串分割函數,若要對字符串進行分割則需自己處理。

首先想到的就是使用string::find函數查找到指定的分隔符,然後通過substr截取子串,來實現字符串的分割。

更方便的方式:C++提供了從輸入流中獲取子串的getline,配合istringstream,即能方便地實現字符串的分割操作:

  • istream& getline (istream& is, string& str, char delim):根據提供的分隔符進行分割;
  • istream& getline (istream& is, string& str):使用換行符分割,能自動處理不同系統下的換行符('\n'或'\r\n');

以提供分隔符爲例(若爲換行符,推薦使用getline (istream& is, string& str)

#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> split(const std::string &strTotal, char chDelim, bool bDiscardEmpty_) {
    vector<string> vecResult;

    string temp;
    istringstream iss(strTotal);
    while (getline(iss, temp, chDelim)) {
        if (bDiscardEmpty_ && temp.empty())
            continue;

        vecResult.push_back(temp);
    }

    return std::move(vecResult);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章