C++ string字符串分割

方法1:采用C语言中的strtok 函数来进行分割
strtok函数包含在头文件<string.h>中,对于字符数组可以采用这种方法处理。当然也可以将字符数组转换成字符串之后再使用法一。测试代码如下

int main()
{
	string str= "a,b*c,d";
	const char *sep = ",*"; //可按多个字符来分割

	char *p;
	p = strtok((char*)str.c_str(), sep);
	while (p){
		printf("%s ", p);
		p = strtok(NULL, sep);
	}
	printf("\n");
	
	system("pause");
	return 0;
}

方法2:

#pragma warning(disable:4996)
#include <iostream>
#include <vector>

using namespace std;


void myStrSplit(vector<int>& v, string &str,const std::string sp)
{
	int posstar = 0;
	size_t pos;
	pos = 0;
	size_t flagpso = str.find(sp, 0);

	//"10086,3433,1234" --- 多端口情况
	if (flagpso != string::npos)//string::npos说明查找没有匹配到
	{
		while ((pos = str.find(sp, pos)) != string::npos)
		{
			cout << "position  " << " : " << pos << endl;
			string v_str = str.substr(posstar, pos-posstar);
			int v_port = atoi(v_str.c_str());
			v.push_back(v_port);

			pos++;
			posstar = pos;
		}
		int size = str.size();
		if (posstar > 0 && posstar < str.size()){
			string v_str = str.substr(posstar, size - posstar);
			int v_port = atoi(v_str.c_str());
			v.push_back(v_port);
		}
	}
	else
	{
		//没找到	//"10086" --- 单端口情况
		int v_port = atoi(str.c_str());
		v.push_back(v_port);
	}
}

int main()
{
	string strport = "10086,3433,1234";
	vector<int> v;
	string spli = ",";
	myStrSplit(v, strport, spli);
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值