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?
Asked
Active
Viewed 165 times
-2

Michał Turczyn
- 32,028
- 14
- 47
- 69

ImFastAFBOIII
- 9
- 1
-
1You 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 Answers
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
-
9No need for `ToCharArray` here - `string` already implements `IEnumerable
` – Jon Skeet Mar 19 '19 at 09:28 -
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