如何从字符串中提取特定元素?
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,但我无法做到。
您可以使用带有模式(\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]; });
相关文章:
- 从C++无序集合中高效提取元素
- 从指向结构数组的指针中提取元素
- 将__m256的奇怪元素提取到__m128中的有效(在锐龙上)方法?
- 在 C++ 中,仅使用递归来提取向量中的最大元素
- 如何从字符串中提取特定元素?
- 从给定的STL容器中提取带有给定谓词的元素到另一个容器
- 正在提取优先级队列的最后一个元素
- 使用犰狳根据行和列索引从矩阵中提取元素
- 提取向量的其他元素
- 提取整数的数字元素
- llvm在C++中提取结构元素和结构大小
- 将元素范围从字符数组提取到字符串中
- 如何提取并检查数组元素中的第一个字符是否为字母
- 提取并转换 boost::p ython::list 的列表元素
- C++:从只能通过迭代器访问的数据类型中高效地提取元素子集
- 对于巨大的数据集,从m个数组的元素组合中提取n个最低和
- 可视化地从c++向量中指定的索引中提取元素
- 按类型和歧义提取元组的元素
- 如何从一对向量中提取第二个元素
- 对于循环-对于每个循环C++,从向量元素中提取