简体   繁体   中英

convert char array to int array c#

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

另一种选择,使用Array.ConvertAllChar.GetNumericValue

int[] Aint = Array.ConvertAll(A, c => (int)Char.GetNumericValue(c));

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.

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.

Please do Like this

  char[] A = {'1', '2', '3', '4'};
  int[] Aint = new int[A.Length];      
  for (int i = 0;i < A.Length;i++)
  {
      Aint[i] = Convert.ToInt32(A[i].ToString()); 
  }

一点点 Linq 应该可以解决问题:

int[] Aint = A.Select(c => c - 48).ToArray(); // or c - '0'

You can also do this:

int[] Aint = A.Select(c => Convert.ToInt32(c.ToString())).ToArray();

This will select all character array as string, converts them to array, then return an integer of array.

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