简体   繁体   English

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

[英]get substring from C string in C++

I have C string 我有C弦

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

I need to take from the string value name, ie, "test" and written in a separate variable. 我需要从字符串值名称(即“ test”)中提取一个单独的变量。

So I need to find the value between "&name=" and the next & 因此,我需要找到“&name =“与下一个&

Because you tagged this as C++ I'll use std::string instead: 因为您将其标记为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("&"));

You could also do this with regex and capture all those values at once, also saving the time of creating a string. 您也可以使用正则表达式执行此操作,并一次捕获所有这些值,还可以节省创建字符串的时间。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM