Nastya Gorobets
Nastya Gorobets

Reputation: 197

get substring from C string in C++

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 &

Upvotes: 0

Views: 5962

Answers (1)

villasv
villasv

Reputation: 6841

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;

Upvotes: 5

Related Questions