Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert char array to int array c#

Tags:

arrays

c#

char

int

I have this array

char[] A = ['1', '2', '3', '4']

And I want to convert it to int[]

int[] Aint=[1, 2, 3, 4]

Any ideas?

I just started programming

Thanks

like image 692
Rud Banisterloid Avatar asked Feb 05 '14 19:02

Rud Banisterloid


3 Answers

Another option, using Array.ConvertAll and Char.GetNumericValue:

int[] Aint = Array.ConvertAll(A, c => (int)Char.GetNumericValue(c));
like image 103
Tim Schmelter Avatar answered Nov 14 '22 11:11

Tim Schmelter


To get the numeric value of a digit character ('0' to '9'), you can simply subtract the codepoint of '0' from its own.

int[] Aint = A.Select(a => a - '0').ToArray();

The digit characters are assigned consecutive codepoints. '0' has codepoint 48; '1' has codepoint 49; and so on until '9', which has codepoint 57. Thus, when you subtract two digit characters, you would get the same result as if you were subtracting their numeric values. Subtracting '0' from any digit would give you the latter's absolute value.

like image 28
Douglas Avatar answered Nov 14 '22 12:11

Douglas


Add a using statement for using System.Linq; then you can do the following:

int[] Aint = A.Select(i => Int32.Parse(i.ToString())).ToArray();

You will get an exception if an element in A cannot be parsed.

like image 6
Adam Modlin Avatar answered Nov 14 '22 13:11

Adam Modlin