我有一个格式为1,3-7,10,11-15的字符串输入 我想识别范围内输入的所有整数。我如何使用C ++实现这一目标?
TIA 顾比
答案 0 :(得分:4)
此问题属于解析域。你会使用解析器。解析器解释一种语言。在您的情况下,语言将如下所示:
input = comma-separated sequence of fragments
fragment = integer or range
range = integer-integer
integer = sequence of digits 0..9
答案 1 :(得分:1)
//Disclaimer -- untested
//Disclaimer -- this is not good code, but it's a quick and dirty way to do this
// if you're trying to see a possible solution.
#include <algorithm>
#include <functional>
#include <vector>
const char input[] = "1,3-7,10,11-15";
const char * inputBegin = input;
const char * inputEnd = input + strlen(input);
std::vector<int> result;
for(; inputBegin < inputEnd; inputBegin = std::find_if(inputBegin, inputEnd, isdigit)) {
int first = *inputBegin - '0';
for(inputBegin++; inputBegin < inputEnd && isdigit(*inputBegin); inputBegin++)
first = first * 10 + (*inputBegin - '0');
int last = first;
if (++inputBegin < inputEnd && *inputBegin == '-') {
last = inputBegin - '0';
for(inputBegin++; inputBegin < inputEnd && isdigit(*inputBegin); inputBegin++)
last = last * 10 + (*inputBegin - '0');
}
for(; first < last; first++)
result.push_back(first);
}