[英]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" 我有一个char数组“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. 我想找到最大值D = 13,但是当我使用for循环查找最大数字时程序不识别D = 13。 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?
相反,它输出D的ascii值,我如何确保每次遇到D时,它会被识别为13而不是它的ascii值?
Thanks guys for your help 谢谢大家帮助
functional recipe: make a map from Char to Int - use Max
: 功能配方:制作从Char到Int的地图 - 使用
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 ;) 在这种情况下得到你
13
;)
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. 顺便说一句:我不知道为什么你想要
14
如果你想要D
为13 - 如果第一个是拼写错误然后你必须改变上面的Map
函数(如果你不想得到幻想,那就是switch
) - as你的第一个定义与Hex所假设的完全相同。
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: 或者,为了确保“D”被转换为“13”,将其从十六进制转换:
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. 请注意
Convert.ToInt32(string, int)
方法,该方法接收数字库以转换字符串表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.