字符串分割经常用到,这里做一个记录。方便查阅。
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);
}
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。