trikker
trikker

Reputation: 2709

How to divide a string into parts - Roman numerals

I'm trying to divide a string into parts for reading Roman numerals. For example if the user enters

"XI"

I want the program to be able to understand that I is 1 and X is 10 in order for a data validation like this to work.

if(string roman == "X") int roman += 10;
 etc.

Upvotes: 2

Views: 730

Answers (2)

chaos
chaos

Reputation: 124335

Function for doing this from a language you don't know, treat as pseudocode:

int from_roman_numeral(string val) {
    val = upper_case(val);
    if(val == "N")
        return 0;
    status neg = False;
    if(val[0] == '-') {
        neg = True;
        val = val[1..];
    }
    int out = 0;
    int last = 0;
    int array values = allocate(127);
    values['M'] = 1000;
    values['D'] = 500;
    values['C'] = 100;
    values['L'] = 50;
    values['X'] = 10;
    values['V'] = 5;
    values['I'] = 1;
    int value;
    int next;
    for(int idx = 0, int len = strlen(val); idx < len; idx++) {
        value = values[val[idx]];
        unless(value)
            error("'" + val + "' is not a valid Roman numeral sequence");
        if(idx < len - 1 && (next = values[val[idx + 1]]) && next > value) {
            out += next - value;
            idx++;
        } else {
            out += value;
        }
    }
    return neg ? -out : out;
}

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 994051

To access an individual character from a string, use square brackets:

int num = 0;
char r = roman[0];
if (r == 'X') {
    num += 10;
}

The above is by no means a complete example, but should be enough to get you started. This example looks at the first character in the string roman (characters are numbered starting at the left with index 0). It checks to see whether the character is 'X', and if so, increments the num variable by 10.

Upvotes: 3

Related Questions