从C ++中的C字符串获取子字符串

时间:2015-11-29 19:59:02

标签: c++ string substring

我有C字符串

   char s[] = "n1=1&n2=2&name=test&sername=test2";

我需要从字符串值名称中取出,即" test"并写在一个单独的变量中。

所以我需要找到"& name ="之间的值。和下一个&

1 个答案:

答案 0 :(得分:4)

因为您将其标记为C ++,我将改为使用std::string

char s[] = "n1=1&n2=2&name=test&sername=test2";
string str(s);
string slice = str.substr(str.find("name=") + 5);

string name = slice.substr(0, slice.find("&"));

您也可以使用正则表达式执行此操作并一次捕获所有这些值,同时节省创建字符串的时间。

char s[] = "n1=1&n2=2&name=test&sername=test2";

std::regex e ("n1=(.*)&n2=(.*)&name=(.*)&sername=(.*)");
std::cmatch cm;
std::regex_match(s,cm,e);

cout << cm[3] << endl;