Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array of chars to an array of integers

I have these arrays

char[] array = {'1', '2', '3', '4'};
int[] sequence = new int[array.Length];  

Is there an easy way to assign the numbers in array to sequence?

I tried this

for (int i = 0; i < array.Length; i++)
{
    seqence[i] = Convert.ToInt32(array[i]);
}

But I get the ASCII coding of 1, 2, 3, 4 not the numbers by itself.

like image 661
Martin Dzhonov Avatar asked Oct 31 '13 13:10

Martin Dzhonov


People also ask

How do I convert a char to an int?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

How do you convert char to int in Python?

ord() : This function is used to convert a character to integer.

How do you assign an int to a char array in Java?

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.

How do you convert a number to a character array?

Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number. Separating integer into digits and accommodate it to a character array.


2 Answers

using System.Linq;

char[] array = { '1', '2', '3', '4' };
var ints = array.Select(x => int.Parse(x.ToString()));
like image 123
Jaycee Avatar answered Sep 21 '22 06:09

Jaycee


Just convert the char to a string first:

for (int i = 0; i < array.Length; i++)
{
     sequence[i] = Convert.ToInt32(array[i].ToString());
}

But of course, you could do this all in a single linq query:

char[] array = {'1', '2', '3', '4'};
int[] sequence = array.Select(c => Convert.ToInt32(c.ToString())).ToArray();
like image 28
p.s.w.g Avatar answered Sep 24 '22 06:09

p.s.w.g