Reputation: 1576
I just started to learn C# and already have a question, maybe quite dumb.
I'm writing a little desktop program (Windows Forms) that checks whether entered bank account number is valid or computes missing control numbers. To check number validity we must multiply each digit in that number by corresponding factor. My problem is:
When I enter whole number (26 digits) in TextBlock control and click Check button I need to parse that number into int array somehow. I saw some examples already 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 FormatException. I also tried
array = inputWindow.Text.Split().Select(h => Int32.Parse(h)).ToArray());
Or something similar but got OverflowException. Int64.Parse resulted in obvious type conversion error. How to accomplish that parsing?
Thanks in advance
EDIT My bad, there was 30 instead of 26, but that actually didn't matter.
Upvotes: 3
Views: 1597
Reputation: 131
This code snippet can be used to convert TextBox text to integer array. But you have to make sure that user will input only interger in 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());
Upvotes: 0
Reputation: 66449
That second snippet is almost there (assuming you want an array of numbers, and that the Text
property has only numbers in it).
Remove the call to Split()
, and the Select()
portion will iterate over each character in the string.
var array = inputWindow.Text.Select(i => Convert.ToInt32(i-48)).ToArray();
Upvotes: 3
Reputation: 39
I just did this in a console application and I was able to get the numbers into the array. I did no math on each one. I assume you could take it from there. I also recommend using a List instead of an array so the size is not 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();
}
}
}
Upvotes: 1
Reputation: 1101
Your whole number just 26 digits,but your i set max is 30 for (int i = 0; i < 30; i++)
, 26 is less than 30,so array[i] = Int32.Parse(numbers[i])
throw OverflowException
Upvotes: 0