好的,所以我需要解析一些信息,我想知道什么是最好的方法来做到这一点。 好的,这里是我需要解析的字符串。分号是“^”用C++中的分隔符解析字符串
John Doe^Male^20
我需要将字符串解析为姓名,性别和年龄变量。 C++中最好的方法是什么?我正在考虑循环,并将条件设置为while(!string.empty()
,然后将所有字符分配到字符串'^',然后清除我已分配的内容。有没有更好的方法来做到这一点?
好的,所以我需要解析一些信息,我想知道什么是最好的方法来做到这一点。 好的,这里是我需要解析的字符串。分号是“^”用C++中的分隔符解析字符串
John Doe^Male^20
我需要将字符串解析为姓名,性别和年龄变量。 C++中最好的方法是什么?我正在考虑循环,并将条件设置为while(!string.empty()
,然后将所有字符分配到字符串'^',然后清除我已分配的内容。有没有更好的方法来做到这一点?
您可以在C++流中使用getline。
istream的&函数getline(istream的&是,串&海峡,字符分隔符=” \ n”)
改变分隔符 '^'
您有几种选择。如果可以使用boost,一个很好的选择是它们在字符串库中提供的分割算法。你可以看看这个使问题在行动中看到的升压答案:How to split a string in c
如果你不能使用boost,您可以使用string::find
得到一个字符的索引:
string str = "John Doe^Male^20";
int last = 0;
int cPos = -1;
while ((cPos = str.find('^', cPos + 1)) != string::npos)
{
string sub = str.substr(last, cPos - last);
// Do something with the string
last = cPos + 1;
}
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
做些什么像这样在一个数组中。
你有很多选择,但我会使用strtok()
,我自己。这将会使这项工作变短。
可能的重复:http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c –