separating number in array of digits C#

514 views Asked by At

i am new in programming and for now only practicing with C#. So my problem is: i am trying to separate a number in a digits with array (example: number 12345 in to digits {1,2,3,4,5}). I make some code, here is it:

  int num = int.Parse(Console.ReadLine());
        int[] digits = new int[3];
        int separatedDigit = 0;


        for (int i = num; num != 0; i--)
        {
            digits[i] = num  % 10;
            num = num / 10;

        }

but it shows me error " Index was outside the bounds of the array." I suppose the problem is coming from that "for" part because it starts from position 3 and the array have only 2 (0, 1, 2). I don't know how to fix it, so can someone help me?

5

There are 5 answers

0
Abion47 On BEST ANSWER

i starts out as equal to num, which in turn starts out as the number that you entered, which can be far greater than 3. For example, if I put in 123 as the input number, then the loop first tries to access digits[123] which is waaaaaay outside the bounds of that array.

You're going to want to tweak your for loop to get i to start at a more reasonable number:

for (int i = digits.Length - 1; num != 0; i--)
{
    // ...

Alternatively, you could start i at 0 and work your way up:

for (int i = 0; num != 0; i++)
{
    // ...
1
Dmitry Bychenko On

Try Linq: filter out '0'..'9' characters and materialize them into array:

int[] digits = Console
  .ReadLine()
  .Where(c => c >= '0' && c <= '9') // '0'..'9' characters only 
  .Select(c => c - '0')             // '0' should correspond to 0 integer
  .ToArray();
0
HonourCode On

The problem is that you haven't allocated the correct number of spaces when initialising the array, for example in the following line of code: int[] digits = new int[3];.. Instead you should first read the input, calculate the number of numbers (characters) that were input and then allocate an array with that number of elements.. Remember that arrays start at the index of 0.. so in your example the first character (number) would be entered at digits[0].. then digits[1]... digit[2].. etc.. from within the loop until all the numbers have been input.

Try this code:

    string numberSequence = Console.ReadLine();
    var numberCount = numberSequence.Length;
    int[] digitArray = new int[numberCount];
    int i = 0;
    foreach (var number in numberSequence)
    {
        digitArray[i] = number;
        Console.WriteLine(number);
        i++;
    }
    Console.ReadLine();
0
Anu Viswan On

Try this

        int _num = 12345;
        var g = _num.ToString().Select(x => int.Parse(x.ToString())).ToArray<int>();
0
Shaahin On

Try this

 string strValue = "19345abc#/";
 char[] charArray = strValue.ToCharArray();
 List<int> list = new List<int>();
 for (int i = 0; i < charArray.Length; i++)
     {
       if (char.IsNumber(charArray[i]))
         {
           list.Add(charArray[i] - '0');
         }
     }