更新时间:2022-10-02 22:52:09
字符串分割经常用到,这里做一个记录。方便查阅。
1.使用strtok();其中
采用strtok(),分隔符可以是多种,如 * ,#中的一种或几种的组合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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(),分隔符只能是一种,如 * ,#中的一种
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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);
}
}
|