C++分割字符串

Python有自带的字符串分割函数,但是C++却没有,于是参考网上各种C++分割字符串的资源,将其整理如下

方法1:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

//字符串分割函数
vector<string> split(string str, string pattern)
{
    string::size_type pos;
    vector<string> result;
    //扩展字符串以方便操作
    str += pattern;
    int size = str.size();
    for (int i = 0; i < size; i++)
    {
        pos = str.find(pattern, i);
        if (pos < size)
        {
            string s = str.substr(i, pos - i);
            result.push_back(s);
            i = pos + pattern.size() - 1;
        }
    }
    return result;
}


int main()
{
    string str = "str1+str2+str3";
    string pattern = "+";
    vector<string> result = split(str, pattern);
    for (int i = 0; i < result.size(); i++)
    {
        cout << result[i] << endl;
    }
    return 0;
}

方法2:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <typeinfo>

using namespace std;
//1、该函数会改变原字符串的值
//2、该函数会根据delimiter里边的每一个字符进行分割,而非把delimiter作为一个整体
//3、相较于strtok()函数,strtok_s函数需要用户传入一个指针,用于函数内部判断从哪里开始处理字符串,其他的使用与strtok()函数相同
int main()
{
	//原始字符串
	char string[] = "A,string*of/tokens and some more,tokens";
	//分隔符
	char delimiter[] = ",*/ ";
	//存储返回结果
	char* result = NULL;
	//context没有过于的作用,只是一个参数而已
	char* context = NULL;
	
	//返回切割的第一个结果
	result = strtok_s(string, delimiter, &context);
	printf("[string]:%s\n", string);
	while (result != NULL) {
		printf("[result]:%s\n", result);
		result = strtok_s(NULL, delimiter, &context);
	}
	return 0;
}

方法3:

#include<string>
#include<vector>
#include<iostream>
using namespace std;

void Tokenize(const string& str, vector<string>& tokens, const string& delimiters)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos = str.find_first_of(delimiters, lastPos);
    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}
int main(int argc, char* argv[])
{
    string str("====aaa==bbb==ccc==ddd====eeee*****eeeee");
    vector<string> results;
    Tokenize(str, results, "=*");
    for (int i = 0; i < results.size(); i++)
    {
        cout << results[i] << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正在修炼的IT大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值