首页 > 编程语言 > 详细

C++字符串分割

时间:2016-08-10 14:37:13      阅读:240      评论:0      收藏:0      [点我收藏+]

字符串分割经常用到,这里做一个记录。方便查阅。


1.使用strtok();其中

采用strtok(),分隔符可以是多种,如 * ,#中的一种或几种的组合

vector<string> stringSplit(string s, const char * split)
{
	vector<string> result;
	const int sLen = s.length();
	char *cs = new char[sLen + 1];
	strcpy(cs, s.data());
	char *p;

	p = strtok(cs, split);
	while (p)
	{
		printf("%s\n", p);
		string tmp(p);
		result.push_back(tmp);
		p = strtok(NULL, split);
	}
	return result;
}


2.使用string.substr();其中

采用string.substr(),分隔符只能是一种,如 * ,#中的一种

vector<string> vec;
int j = 0;
for (int i = 0; i<str.size(); i++){

	if (str[i] == ‘ ‘){
		string tmp = str.substr(j, i - j);
		vec.push_back(tmp);
		j = i + 1;
	}
	if (i == str.size() - 1){
		string tmp = str.substr(j, i - j + 1);
		vec.push_back(tmp);
	}

}


本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1836430

C++字符串分割

原文:http://qiaopeng688.blog.51cto.com/3572484/1836430

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!