这样的字符串什么分割啊?
字符串:12345,"wwwe,445576fd,adsfewr",ttyet56y
要求按逗号“,”分割成3段:
str[0]=12345
str[1]="wwwe,445576fd,adsfewr"
str[2]=ttyet56y
最好用正则表达式可以达到目的,如果是自己写代码分割,最好是c或c++;
先谢谢各路大虾!
[解决办法]
直接贴代码了,利用简单的状态机。
std::vector<std::string> split_string(const std::string& str)
{
enum
{
S_INIT = 0,
S_ID = 1,
S_STRING = 2,
};
std::vector<std::string> vec_string;
const char* cp = str.c_str();
int state = S_INIT;
std::string item;
while (*cp)
{
switch (state)
{
case S_INIT:
item.clear();
if (*cp == '"')//find the beginning of string.
{
state = S_STRING;
item.push_back(*cp);
}
else if (*cp != ',')//find the beginning of id.
{
state = S_ID;
}
break;
case S_ID:
if (*cp == ',')//end of id.
{
vec_string.push_back(item);
state = S_INIT;
}
else
{
item.push_back(*cp);
}
break;
case S_STRING:
item.push_back(*cp);
if (*cp == '"')//end of string.
{
vec_string.push_back(item);
state = S_INIT;
}
break;
}
cp++;
}
if (state == S_ID)
{
vec_string.push_back(item);
}
return vec_string;
}