[英]How to extract specific elements from a string?
我試圖從下一個字符串的每個數字塊中提取第一個數字。
string s = "f 1079//2059 1165//2417 1164//2414 1068//1980";
在此示例中,我需要提取1079、1165、1164和1068
我已經嘗試過使用getline和substr,但是我卻不能。
您可以將<regex>
(C ++正則表達式庫)與模式(\\\\d+)//
。 在雙斜杠前找到數字。 還使用括號僅通過子匹配來提取數字。
這是用法。
string s = "f 1079//2059 1165//2417 1164//2414 1068//1980";
std::regex pattern("(\\d+)//");
auto match_iter = std::sregex_iterator(s.begin(), s.end(), pattern);
auto match_end = std::sregex_iterator();
for (;match_iter != match_end; match_iter++)
{
const std::smatch& m = *match_iter;
std::cout << m[1].str() << std::endl; // sub-match for token in parentheses, the 1079, 1165, ...
// m[0]: whole match, "1079//"
// m[1]: first submatch, "1070"
}
我通常會為這種事情尋求istringstream
幫助:
std::string input = "f 1079//2059 1165//2417 1164//2414 1068//1980";
std::istringstream is(input);
char f;
if (is >> f)
{
int number, othernumber;
char slash1, slash2;
while (is >> number >> slash1 >> slash2 >> othernumber)
{
// Process 'number'...
}
}
這是使用getline和substring的嘗試。
auto extractValues(const std::string& source)
-> std::vector<std::string>
{
auto target = std::vector<std::string>{};
auto stream = std::stringstream{ source };
auto currentPartOfSource = std::string{};
while (std::getline(stream, currentPartOfSource, ' '))
{
auto partBeforeTheSlashes = std::string{};
auto positionOfSlashes = currentPartOfSource.find("//");
if (positionOfSlashes != std::string::npos)
{
target.push_back(currentPartOfSource.substr(0, positionOfSlashes));
}
}
return target;
}
或者有另一種分離的方式來提取令牌,但是它可能涉及一些字符串復制。
考慮如下的split_by
函數
std::vector<std::string> split_by(const std::string& str, const std::string& delem);
使字符串被分割 首先,然后由
//
拆分並提取第一項。
std::vector<std::string> tokens = split_by(s, " ");
std::vector<std::string> words;
std::transform(tokens.begin() + 1, tokens.end(), // drop first "f"
std::back_inserter(words),
[](const std::string& s){ return split_by(s, "//")[0]; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.