如何从字符串中提取特定元素?

How to extract specific elements from a string?

本文关键字:元素 提取 字符串      更新时间:2023-10-16

我正在尝试从下一个字符串的每个数字块中提取第一个数字。

string s = "f 1079//2059 1165//2417 1164//2414 1068//1980";

在这个例子中,我需要提取 1079、1165、1164 和 1068

我已经尝试过 getline 和 substr,但我无法做到。

您可以使用带有模式(\d+)//<regex>(C++正则表达式库)。找到双斜杠前的数字。还使用括号仅通过子匹配提取数字。

这是用法。

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和子字符串的尝试。

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);

在C++中拆分字符串中可能的实现?

使字符串首先被拆分,然后被CC_6拆分并提取第一项。

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]; });