自定义C++的字符串分割函数

C#可以直接使用函数库自带的split
C++不行,
所以利用string的find函数和substr函数自己写了一个。

这里是引用

测试结果如下:

在这里插入图片描述

测试代码如下:

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

using namespace std;

//字符串分割函数
void split(vector<string>& result, string str, string pattern) {
    string::size_type pos;
    int sizep = pattern.size();
    int sizes = str.size();
    int head = 0, index = 0;

    if (str.find(pattern, index) == 0)//pattern在最前面(避免空串)
        index++, head = sizep;

    while ((pos = str.find(pattern, index)) != -1) {
        result.push_back(str.substr(head, pos - head));
        index = pos + sizep;
        head = pos + sizep;
    }
    if (head != 0 && head != sizes)  // pattern没有和pattern在最后面2种情况
        result.push_back(str.substr(head, sizes - head));
}

// substr(x,0)返回 "" 不是NULL
int main() {
    vector<string> chr;
    split(chr, ",dasfdsaf,dsaf,fdsa,df,", ",");
    for (auto i : chr)
        cout << i << " ";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值