在C++中实现字符串分割--split

字符串分割

在一些比较流行的语言中,字符串分割是一个比较重要的方法,不论是在python,java这样的系统级语言还是js这样的前端脚本都会在用到字符串的分割,然而在c++中却没有这样的方法用来调用。但是在boost中却提供分割方法。

使用vector实现

下面是用vector实现的一个简单的split函数,借助string::find函数查找匹配子串的位置,然后截取剩下的字符串之后继续处理,实现对原字符串的完整处理。

#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;
}
posted @ 2016-05-01 23:03  听雨阁中听雨歌  Views(2162)  Comments(0Edit  收藏  举报