This question is different as it tackles the issue of converting a char to an int when adding to an integer array.
The following piece of code, I am trying to implement a string of integers into a int[] array in C#.
My desired output is an array of:
12345678910
This is my code, however, the output of this is not what I desire:
string numbers = "12345678910";
int[] array = new int[numbers.Length];
for (int i = 1; i <= numbers.Length; i++)
{
array[i - 1] = numbers[i-1];
}
foreach(var y in array)
{
Console.Write(y);
}
Output of given code:
4950515253545556574948
Can somebode tell me why I am getting this output, and what I can do to fix this? Thank you!
Edit: Changed my code and it works using this:
for (int i = 0; i < numbers.Length; i++)
{
array[i] = int.Parse(numbers[i].ToString());
}
Charobjects can be converted tointimplicitly. You could usenumbers.Select(c=>(int)c-'0').ToArray()to get an array of numbers from the string.forloop is unnecessarily redundant.for (int i = 1; i <= numbers.Length; i++) array[i - 1] = numbers[i-1];can be written a lot easier such asfor (int i = 0; i < numbers.Length; i++) array[i] = numbers[i];-- Using this approach, you don't have to remember to puti-1in every index accessor.for (int i = 0; i < numbers.Length; i++you don't have to do the wholei - 1to get the right index