-2

So I'm writing a program for a barcodescanner in C# .NET 3.5. When I scan the barcode I get an string with just numbers and I want that string to split at every number and put each number into an int array, but I can´t figure out how. Does someone of you know how to do that?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • 1
    You haven´t tried out much, do you? Shouldn´t be that hard to google this. Apart from this please provide some sample input and the expected output. – MakePeaceGreatAgain Mar 19 '19 at 09:29

2 Answers2

8

Try this:

int[] array = "1234567890".ToCharArray().Select(c => int.Parse(c.ToString())).ToArray();

You can omit method invocation of ToCharArray as string is already collection of chars :)

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
1

There are multiple ways to convert a char into a integer

char digit = '0';

int result = (int)char.GetNumericValue(digit);
int result = ((int)digit) - 48;
int result = digit - '0'; //fastest approach
int result = int.Parse(digit.ToString());
int result = Convert.ToInt32(digit.ToString());
int result = digit & 0x0f;

so if you want the most performant approach then use

string input = "123";
int[] result = input.Select(x => x - '0').ToArray();
fubo
  • 44,811
  • 17
  • 103
  • 137