My original string looks like this <Information name="Identify" id="IdentifyButton" type="button"/>
from this string, how do extract 3 substrings string name_part = Identify
, string id_part="IdentifyButton"
, type_part="button"
My original string looks like this <Information name="Identify" id="IdentifyButton" type="button"/>
from this string, how do extract 3 substrings string name_part = Identify
, string id_part="IdentifyButton"
, type_part="button"
Assuming you don't want to use third-party XML parsers, you can simply use std::string
's find()
for each of your names:
int main()
{
std::string s("<Information name = \"Identify\" id = \"IdentifyButton\" type = \"button\" / >");
std::string names[] = { "name = \"" , "id = \"" , "type = \"" };
std::string::size_type posStart(0), posEnd(0);
for (auto& n : names)
{
posStart = s.find(n, posEnd) + n.length();
posEnd = s.find("\"", posStart);
std::string part = s.substr(posStart, posEnd - posStart);
std::cout << part << std::endl;
posEnd++;
}
}
Add error checking per your tolerance :)
You could use a regex to extract key-value pairs separated by a '=' with optional space characters in between:
(\S+?)\s*=\s*([^ />]+)
[^ />]+
captures a value consisting of characters other than space, / and >. This will capture values with or without quotes.
Then use std::regex_iterator, a read-only forward iterator, that will call std::regex_search() with the regex. Here's an example:
#include <string>
#include <regex>
#include <iostream>
using namespace std::string_literals;
int main()
{
std::string mystring = R"(<Information name="Identify" id="IdentifyButton" type="button" id=1/>)"s;
std::regex reg(R"((\S+?)\s*=\s*([^ />]+))");
auto start = std::sregex_iterator(mystring.begin(), mystring.end(), reg);
auto end = std::sregex_iterator{};
for (std::sregex_iterator it = start; it != end; ++it)
{
std::smatch mat = *it;
auto key = mat[1].str();
auto value = mat[2].str();
std::cout << key << "_part=" << value << std::endl;
}
}
Output:
name_part="Identify"
id_part="IdentifyButton"
type_part="button"
id_part=1
Here's a Demo. Requires at least C++11.