简体   繁体   中英

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.

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.

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.

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. 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.

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.

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' . This returns how far away your number is from the '0' character, thus the 0..9 value you are looking for. It just so happens that the characters '0'..'9' are after each other (it just makes sense, but it's not necessarily so).

You can also try int.Parse on a single character or the whole string. That also handles the usual decimal digits as you would expect.

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