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

get substring from C string in C++

本文关键字:字符串 获取 C++ 中的      更新时间:2023-10-16

我有C字符串

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

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

所以我需要找到"&name="和下一个&

因为您将其标记为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("&"));

您还可以使用regex一次捕获所有这些值,从而节省创建字符串的时间。

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;