2

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

Guppy
  • 31
  • 1

2 Answers2

4

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
  • 173,980
  • 10
  • 155
  • 350
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);
}
Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • +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 Apr 19 '10 at 15:26
  • this code is scary. downright disgusting, really. but I won't downvote you for the same reason wheaties mentioned. – rmeador Apr 19 '10 at 15:32
  • It looks more scary than it is due to the lack of whitespace and calming green comments. – graham.reeds Apr 20 '10 at 08:00