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

字符串分割

在一些比較流行的語言中,字符串分割是一個比較重要的方法,不管是在python,java這樣的系統級語言仍是js這樣的前端腳本都會在用到字符串的分割,然而在c++中卻沒有這樣的方法用來調用。可是在boost中卻提供分割方法。前端

使用vector實現

下面是用vector實現的一個簡單的split函數,藉助string::find函數查找匹配子串的位置,而後截取剩下的字符串以後繼續處理,實現對原字符串的完整處理。java

#include<iostream>
#include<vector>
#include<string>

using namespace std;

vector<string> split(string &s, string &delim, bool removeEmpty = false, bool fullMatch = false) {
    vector<string> result;
    string::size_type start = 0, skip = 1;

    // 使用整個字符串進行查找,以後會直接跳過整個子字符串
    if (fullMatch) {
        skip = delim.length();
    }

    while (start != string::npos) {
        // 從start位置開始查找子字符串delim第一次出現的位置
        string::size_type finsh = s.find(delim, start);

        if (skip == 0) {
            finsh = string::npos;
        }

        // 從start開始到(finsh - start)處得到子字符串
        // 得到匹配字符串以前的字符串
        string token = s.substr(start, finsh - start);

        // 對token進行判斷並決定是否移除空
        if (!(removeEmpty && token.empty())) {
            // 將匹配字符串以前的字符串放進向量中
            result.push_back(token);
        }

        // 判斷此時是否到了原字符串的末尾
        if ((start = finsh) != string::npos) {
            // 將子字符串放進向量中,是爲了保證原字符串的字符不丟失
            result.push_back(delim);
            // 將查找位置向前移動skip個位置
            start = start + skip;
        }
    }

    return result;
}

int main() {
    string x = "hello,,world",
            delim = ",";
    vector<string> xx = split(x, delim, true, true);
    for (auto item:xx) {
        cout << item << endl;
    }
    cout << "finsh" << endl;
    return 0;
}
相關文章
相關標籤/搜索