![](/img/trans.png)
[英]how do i extract multiple substrings from a single string separated by space?
[英]How to extract multiple substrings from a string?
我的原始字符串如下所示<Information name="Identify" id="IdentifyButton" type="button"/>
從這個字符串中,如何提取 3 個子string name_part = Identify
, string id_part="IdentifyButton"
, type_part="button"
假設您不想使用第三方 XML 解析器,您可以簡單地為每個名稱使用std::string
的find()
:
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++;
}
}
根據您的容忍度添加錯誤檢查:)
您可以使用正則表達式來提取由“=”分隔的鍵值對,中間有可選的空格字符:
(\S+?)\s*=\s*([^ />]+)
[^ />]+
捕獲由空格、/ 和 > 以外的字符組成的值。 這將捕獲帶引號或不帶引號的值。
然后使用std::regex_iterator ,一個只讀的前向迭代器,它將使用正則表達式調用std::regex_search() 。 這是一個例子:
#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
這是一個演示。 至少需要 C++11。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.