0

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());
}
kieron
  • 332
  • 3
  • 19

1 Answers1

2

First of all, I don't think you'll be able to distinguish a two digit number using this method.

I refer to this part of your code: string numbers = "12345678910"; Iterate through your string characters and parse to Int (if that's what's required) (credit) (credit)

 foreach (char character in yourString)
        {
            int x = (int)Char.GetNumericValue(character);                
            //code to add to your array of ints
        }
tonycdp
  • 137
  • 2
  • 9