c++分割字符串方法
char*类型
使用c库函数strtok
函数原型: char *strtok(char *str, const char *delim);
分割字符串返回一串字符;
strtok会将分类字符‘,’改为‘\0’,strtok之间会有缓存(使用NULL,继续分割)
#include<iostream>
using namespace std;
int main() {
char str[] = "1,2,3,4,5,6";
char split = ',';
char* ans;
ans = strtok(str, &split);
//返回(char*)的1
while (ans != nullptr) {
cout << *ans << " ";
ans = strtok(NULL, &split);
//继续分割,返回剩下字符
}
}
string类型
使用find+substr函数
函数原型:string substr ( size_t pos = 0, size_t n = npos ) const;
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
string str = "1,2,3,4,5,6";
vector<string>ans;
char split = ',';
int str_len = str.size();
int spos = 0;
//开始找的位置
int epos = 0;
//找到的首位置
while(epos =str.find(split, spos))
if (epos == -1) {
//等于-1说明没有‘,’了但还有一个6要拿出来
string temp = str.substr(spos, str_len - spos);
ans.push_back(temp);
break;
}
else {
string temp = str.substr(spos, epos - spos);
//分割spos到epos的字符
ans.push_back(temp);
spos = epos + 1;
//越过‘,’继续找
}
for (auto x : ans) {
cout << x << " ";
}
}