方法1:采用C语言中的strtok 函数来进行分割
strtok函数包含在头文件<string.h>中,对于字符数组可以采用这种方法处理。当然也可以将字符数组转换成字符串之后再使用法一。测试代码如下
int main()
{
string str= "a,b*c,d";
const char *sep = ",*"; //可按多个字符来分割
char *p;
p = strtok((char*)str.c_str(), sep);
while (p){
printf("%s ", p);
p = strtok(NULL, sep);
}
printf("\n");
system("pause");
return 0;
}
方法2:
#pragma warning(disable:4996)
#include <iostream>
#include <vector>
using namespace std;
void myStrSplit(vector<int>& v, string &str,const std::string sp)
{
int posstar = 0;
size_t pos;
pos = 0;
size_t flagpso = str.find(sp, 0);
//"10086,3433,1234" --- 多端口情况
if (flagpso != string::npos)//string::npos说明查找没有匹配到
{
while ((pos = str.find(sp, pos)) != string::npos)
{
cout << "position " << " : " << pos << endl;
string v_str = str.substr(posstar, pos-posstar);
int v_port = atoi(v_str.c_str());
v.push_back(v_port);
pos++;
posstar = pos;
}
int size = str.size();
if (posstar > 0 && posstar < str.size()){
string v_str = str.substr(posstar, size - posstar);
int v_port = atoi(v_str.c_str());
v.push_back(v_port);
}
}
else
{
//没找到 //"10086" --- 单端口情况
int v_port = atoi(str.c_str());
v.push_back(v_port);
}
}
int main()
{
string strport = "10086,3433,1234";
vector<int> v;
string spli = ",";
myStrSplit(v, strport, spli);
}