tags:

views:

89

answers:

2

Hello,

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 using C++?

TIA Guppy

+4  A: 

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
MSalters
+1  A: 
//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);
}
Billy ONeal
+1 for anyone who openly admits that while it works, it's not the best solution. Wish more people would do that on their blogs.
wheaties
this code is scary. downright disgusting, really. but I won't downvote you for the same reason wheaties mentioned.
rmeador
It looks more scary than it is due to the lack of whitespace and calming green comments.
graham.reeds