简体   繁体   English

如何将字符串的字符转换为整数数组

[英]How to convert a string's chars into an array of ints

I am trying to take the user's input and convert it into an array of ints. 我试图接受用户的输入并将其转换为整数数组。 The problem is that when I choose 4 numbers, eg 2463 the output for the string is correct, but the output for the int array is incorrect and seems to be the number chosen + 48. 问题是,当我选择4个数字(例如2463)时,字符串的输出正确,但是int数组的输出不正确,似乎是选择的数字+ 48。

I'm not really sure why this is occurring. 我不太确定为什么会这样。 Thanks for any help given. 感谢您提供的任何帮助。

string userChoiceAsString;
int[] userChoice = new int[4];

userChoiceAsString = (Console.ReadLine());

for (int i = 0; i < userChoiceAsString.Length; i++)
{
    userChoice[i] = userChoiceAsString[i];
    Console.WriteLine(userChoice[i]);
    Console.WriteLine(userChoiceAsString[i]);
}

This is reasonable, because when a user inputs the character 2, this corresponds to the decimal 50. This is associated with the ASCII table. 这是合理的,因为当用户输入字符2时,它对应于小数点50。这与ASCII表相关联。

Please have a look here . 在这里看看。

In order to avoid this, you should try to parse the each character, like below: 为了避免这种情况,您应该尝试解析每个字符,如下所示:

userChoice[i] = Int32.Parse(userChoiceAsString[i].ToString());

or you could make use of Char's method GetNumericValue which returns a float number and then cast this to an int. 或者您可以使用Char的方法GetNumericValue ,该方法返回一个浮点数,然后将其GetNumericValue转换为int。

userChoice[i] = (int)Char.GetNumericValue(userChoiceAsString[i]);

您需要使用int.Parse()将ASCII值转换为int,否则将打印ASCII值。

尝试:

userChoice[i] = (int)Char.GetNumericValue(userChoiceAsString[i]);

The number 0 that we all know is represented by the character that has a numerical value of 48 in ASCII, Unicode and several other character sets. 众所周知,数字0由以ASCII,Unicode和其他几种字符集表示的数值为48的字符表示。 The letter A is 65, etc. This has literally nothing to do with the actual numerical value, since characters also represent letters and millions of other glyphs which have no numerical value. 字母A是65,以此类推。这实际上与实际数值无关,因为字符还代表字母和数百万个没有数值的其他字形。

You can look at the Char.GetNumericValue method, but note that it also returns the numerical value of pi, e, and other numerals from all kinds of character sets. 您可以查看Char.GetNumericValue方法,但请注意,它还会返回pi,e以及来自各种字符集的其他数字的数值。

What we usually do is check if the character is between '0' and '9' , and if so, get the value as (int)ch - (int)'0' . 我们通常要做的是检查字符是否在'0''9' ,如果是,则将值获取为(int)ch - (int)'0' This returns how far away your number is from the '0' character, thus the 0..9 value you are looking for. 这将返回您的数字与'0'字符的距离,即您要查找的0..9值。 It just so happens that the characters '0'..'9' are after each other (it just makes sense, but it's not necessarily so). 碰巧字符'0'..'9'接连出现(这很有意义,但不一定如此)。

You can also try int.Parse on a single character or the whole string. 您也可以尝试对单个字符或整个字符串进行int.Parse That also handles the usual decimal digits as you would expect. 这也可以像您期望的那样处理通常的十进制数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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