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.
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.
ord() : This function is used to convert a character to integer.
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.
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.
using System.Linq;
char[] array = { '1', '2', '3', '4' };
var ints = array.Select(x => int.Parse(x.ToString()));
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With