简体   繁体   English

将char数组转换为int数组c#

[英]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[]

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.要获得数字字符的数值( '0''9' ),您可以简单地从其自身中减去'0'的代码点。

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

The digit characters are assigned consecutive codepoints.数字字符被分配连续的代码点。 '0' has codepoint 48 ; '0'代码点为48 '1' has codepoint 49 ; '1'代码点为49 and so on until '9' , which has codepoint 57 .依此类推,直到'9' ,其代码点为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.从任何数字中减去'0'将为您提供后者的绝对值。

Add a using statement for using System.Linq;using System.Linq;添加 using 语句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.如果无法解析A的元素,您将收到异常。

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.这将选择所有字符数组作为字符串,将它们转换为数组,然后返回数组的整数。

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

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