0

I have C string

   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.

So I need to find the value between "&name=" and the next &

5
  • You could build an std::string and use substr Commented Nov 29, 2015 at 20:01
  • So you'd use strlen() to find an end iterator, std::search() to find the position of the where the parameter starts, and std::find() where it ends. What part exactly is your problem? Commented Nov 29, 2015 at 20:02
  • You can use the pointer as an array. Commented Nov 29, 2015 at 20:02
  • FWIW, s should be const here. Commented Nov 29, 2015 at 20:06
  • As a generic solution, you could first split on & to get the collection of pairs (a=b), then split on = to get a key and value for each pair. Commented Nov 29, 2015 at 22:39

1 Answer 1

5

Because you tagged this as C++ I'll use std::string instead:

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.It is that I need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.