字符串分割的c++实现方式


一边遍历一边分割:

<span style="white-space:pre">	</span>// split -> vector

	std::vector<Point> points;
	
	std::string lo = "2,1 2,2 2,4 4,3 ";
	for (int p1 = 0, p2 = 0; (p2 = lo.find(" ", p1 + 1)) >= 0; p1 = p2)
	{
		std::string sub = lo.substr(p1, p2);
		{
			int x = 0;
			int y = 0;
			sscanf(sub.c_str(), "%d,%d", &x, &y);
			
			points.push_back( Point(x,y) );
		}
	};


方法1:

	char str[] = "a,b,c,d*e";
	const char * seprator = ",";
	char * p = strtok(str, seprator);
	while (p)
	{
		CCLOG("%s\n", p);
		p = strtok(NULL, seprator);
	}


方法2:
void strSplit(std::string str, const char* seprator, std::vector<std::string>& strs_out);


void SceneBattleField::strSplit(std::string str, const char* seprator, std::vector<std::string>& strs_out)
{
	int pos = 0;
	int pos_start = 0;
	int seplen = strlen(seprator);

	do
	{
		pos = str.find(seprator, pos_start);
		if (pos > 0)
			strs_out.push_back(str.substr(pos_start, pos - pos_start));
		else
			strs_out.push_back(str.substr(pos_start));
		pos_start = pos + seplen;

	} while (pos > 0);
}

std::string strSplitAt(std::string str, const char* seprator, int index);

// 字符串分割,直接获取某个分割位上的字符。index从0开始
std::string strSplitAt(std::string str, const char* seprator, int index)
{
	std::string strRet = "";

	int pos = 0;
	int pos_start = 0;
	int seplen = strlen(seprator);

	int i = 0;
	do
	{
		pos = str.find(seprator, pos_start);

		if (i == index)
		{
			if (pos > 0)
				strRet = str.substr(pos_start, pos - pos_start);
			else
				strRet = str.substr(pos_start);
		}

		pos_start = pos + seplen;
		i++;
	} while (pos > 0);

	return strRet;
}


调用例子:

	char * str = "a,*b,*c,*d*e";

	std::vector<std::string> strs;
	strSplit(str, ",*", strs);

	std::string str2 = strSplitAt(str, ",*", 0);


[0] 0x9bf21c
[1] 0x9bf55c




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值