How to split a long entered into a TextBox control into an array of int

I just started learning C # and have already asked a question, maybe completely dumb.

I am writing a small desktop program (Windows Forms) that checks if the entered bank account number is valid or calculates missing control numbers. To check if the number is correct, we must multiply each digit by that number by the appropriate coefficient. My problem:

When I enter an integer (26 digits) in the TextBlock control and click the Validate button, I need to somehow divide that number into an array. I have already seen some examples and tried

int[] array = new int[26];
char[] sep = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

String[] numbers = inputWindow.Text.Split(sep);

for (int i = 0; i < 26; i++)
    array[i] = Int32.Parse(numbers[i]);

      

But got a FormatException. I have also tried

array = inputWindow.Text.Split().Select(h => Int32.Parse(h)).ToArray());

      

Or something similar, but got an OverflowException. Int64.Parse resulted in an obvious type conversion error. How do you do this parsing?

Thank you in advance

EDIT My bad, it was 30 instead of 26, but that didn't really matter.

+3


source to share


4 answers


This second snippet almost exists (assuming you want an array of numbers and that the property Text

only has numbers in it).

Remove the call Split()

and the part Select()

will iterate over every character in the string.



var array = inputWindow.Text.Select(i => Convert.ToInt32(i-48)).ToArray();

      

+3


source


I just did this in a console application and I was able to get the numbers in the array. I didn't do math. I suppose you could take it from there. I also recommend using a List instead of an array so that the size doesn't get fixed.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
        Console.Write("Number: ");
        string inputStr = Console.ReadLine();
        int[] array = new int[30];

        int i = 0;
        foreach(Char c in inputStr)
        {
            array[i] = Convert.ToInt32(c.ToString());
            i++;
        }

        Console.WriteLine("");

        foreach (int num in array)
        {
            Console.WriteLine(num.ToString());
        }

        Console.ReadLine();
    }
  }
}

      

+1


source


Your whole number is only 26 digits, but your i max is 30 for (int i = 0; i < 30; i++)

, 26 is less than 30, so array[i] = Int32.Parse(numbers[i])

throw OverflowException

0


source


This code snippet can be used to convert TextBox text to an integer array. But you have to make sure that the user will only enter interger in the textBox.

  int[] array = new int[30];
        char[] sample = textBox1.Text.ToCharArray();

        for (int i = 0; i < 26; i++)
            array[i] = int.Parse(sample[i].ToString());

      

0


source







All Articles