您的位置:首页 > 编程语言 > C语言/C++

C++字符串分割

2016-08-10 10:50 211 查看
字符串分割经常用到,这里做一个记录。方便查阅。

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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串