[英]How can I extract integers from a string?
考虑一个形式的字符串
“列数 = 5
行数 = 345
1 3 -5 2 9
4 -10 34 -22 7"
[后面还有 343 行。 不过,我想这足以解释问题了。]
我希望将值5
和345
提取为整数。 子字符串“列数=”和“行数=”是已知的,但这些字符串后面的值中的位数是未知的。 但是,已知相应的行在值之后结束。 我可以使用以下代码到达数字的开头
std::string searchString = "clause length = ";
int searchStringLength = searchString.length();
std::size_t startAt = result.find(searchString) + searchStringLength;
但是,我不知道如何检测行尾,使用它可以提取值。
下一部分是提取其余的整数并将它们存储在一个数组中,我想如果我能识别空格和行尾的位置,这个问题也将得到解决。
如何有效地解决这个问题[我使用的是 Visual Studio 2017]?
尝试以下基于正则表达式的简单数字提取器
#include <iostream>
#include <iterator>
#include <string>
#include <regex>
int main()
{
std::string s = "number of columns = 5\n"
"number of rows = 345\n"
"1 3 -5 2 9\n"
"4 -10 34 -22 7\n";
std::regex num_regex("\\d+|-\\d+");
auto num_begin =
std::sregex_iterator(s.begin(), s.end(), num_regex);
auto num_end = std::sregex_iterator();
for (std::sregex_iterator i = num_begin; i != num_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
std::cout << " " << match_str << '\n';
}
}
输出
5
345
1
3
-5
2
9
4
-10
34
-22
7
您可以将字符串拆分为标记。 在这种情况下,根据“=”符号拆分字符串,然后尝试将它们转换为整数的http://www.cplusplus.com/reference/cstring/strtok/通过此链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.