简体   繁体   中英

Finding highest value in array however with assigned numbers to characters

i have a quick question

A = 10
B = 11
C = 12
D = 13

I have an char array "5623ADCB"

I would want to find the biggest value which is D = 13 but the program doesn't recognize D = 13 when i use a for loop to look for the biggest number. Instead it outputs the D's ascii value, how do i make ensure that everytime a D is encountered, it would be recognized as 13 and not it's ascii value?

Thanks guys for your help

functional recipe: make a map from Char to Int - use Max :

static int Map(char c)
{
    return Int32.Parse (c.ToString(), System.Globalization.NumberStyles.HexNumber);
}

var max = "5623ADCB".Select (Map).Max ();

get's you 13 in this case ;)


here is a version if you are concerned with memory and performance:

static int FindMax(string s)
{
    s = s.ToUpper ();
    var max = 0;
    for (int i = 0; i < s.Length; i++) {
        var v = Map (s [i]);
        if (v > max)
            max = v;
    }
    return max;
}

static int Map(char c)
{
    if (c >= '0' && c <= '9')
        return (int)c - (int)'0';
    if (c >= 'A' && c <= 'E')
        return (int)c - (int)'A' + 10;

    throw new ArgumentOutOfRangeException ();
}

btw: I have no clue why you want 14 if you want D to be 13 - if the first was a typo then you have to change the Map function above (a switch will do if you don't want to get fancy) - as your first definition was exactly the same you would assume from Hex I went with it.

Do you need to get the greater value?

var array = "5623ADCB".ToCharArray();
Console.WriteLine(array.Max());

Or, to make sure "D" gets translated to "13", transform it from hexadecimal:

var array = "5623ADCB".ToCharArray();
Console.WriteLine(Convert.ToInt32(array.Max().ToString(), 16));

Notice the Convert.ToInt32(string, int) method, which receives the numeric base to translate the string expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM