我有一个格式为1,3-7,10,11-15的字符串输入,我想标识范围内输入的所有整数。如何使用C++实现这一点?
TIA Guppy
发布于 2010-04-19 22:23:57
这个问题属于句法分析领域。你可以使用解析器。解析器解释一种语言。在您的示例中,语言将如下所示:
input = comma-separated sequence of fragments
fragment = integer or range
range = integer-integer
integer = sequence of digits 0..9发布于 2010-04-19 23:18:43
//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);
}https://stackoverflow.com/questions/2668107
复制相似问题