问题描述
在 C++ 中给定一个包含范围和单个数字的字符串:
Given a string in C++ containing ranges and single numbers of the kind:
"2,3,4,7-9"
我想将其解析为以下形式的向量:
I want to parse it into a vector of the form:
2,3,4,7,8,9
如果数字由 -
分隔,那么我想推送范围内的所有数字.否则我想推送一个数字.
If the numbers are separated by a -
then I want to push all of the numbers in the range. Otherwise I want to push a single number.
我尝试使用这段代码:
const char *NumX = "2,3,4-7";
std::vector<int> inputs;
std::istringstream in( NumX );
std::copy( std::istream_iterator<int>( in ), std::istream_iterator<int>(),
std::back_inserter( inputs ) );
问题是它不适用于范围.它只取字符串中的数字,而不是范围内的所有数字.
The problem was that it did not work for the ranges. It only took the numbers in the string, not all of the numbers in the range.
推荐答案
除了@J.Schultke 的优秀例子,我建议以下列方式使用正则表达式:
Apart from @J. Schultke's excellent example, I suggest the use of regexes in the following way:
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
void process(std::string str, std::vector<int>& num_vec) {
str.erase(--str.end());
for (int i = str.front() - '0'; i <= str.back() - '0'; i++) {
num_vec.push_back(i);
}
}
int main() {
std::string str("1,2,3,5-6,7,8");
str += "#";
std::regex vec_of_blocks(".*?\,|.*?\#");
auto blocks_begin = std::sregex_iterator(str.begin(), str.end(), vec_of_blocks);
auto blocks_end = std::sregex_iterator();
std::vector<int> vec_of_numbers;
for (std::sregex_iterator regex_it = blocks_begin; regex_it != blocks_end; regex_it++) {
std::smatch match = *regex_it;
std::string block = match.str();
if (std::find(block.begin(), block.end(), '-') != block.end()) {
process(block, vec_of_numbers);
}
else {
vec_of_numbers.push_back(std::atoi(block.c_str()));
}
}
return 0;
}
当然,您仍然需要一点验证,但是,这会让您开始.
Of course, you still need a tad bit validation, however, this will get you started.
这篇关于在 C++ 中解析逗号分隔的整数/整数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!