开发者

How do I convert a range of integers into a list using C++

I have a string input of the format 1,3-7,10,11-15 I want to identify all the integers entered in the range. How do I achieve this usin开发者_运维技巧g C++?

TIA Guppy


This problem belongs to domain of parsing. You'd use a parser. A parser interprets a language. In your case, the language will look like something like this:

input = comma-separated sequence of fragments
fragment = integer or range
range = integer-integer
integer = sequence of digits 0..9


//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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜