2

I have a int number = 1782901998 whose Length is 10 numbers; I need to split them into 10 different strings. I tried the following code, but it does not give back any output; I need to assign the each number to a string.

string number = 7894;
char[] numberChars = number.ToString().ToCharArray();
int[] digits = new int[numberChars.length];

for(int i = 0; i < numberChars.length; i++) {

    digits[i] = (int)numberChars[i];

 }

This code only returns 57 in digits list.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Martin j
  • 511
  • 1
  • 9
  • 31
  • 1
    This code fills an array of integers with the ASCII code for the characters '7', '8', '9', and '4' (55,56,57,52). (By the way it doesn't even compile) – Steve Dec 20 '16 at 10:29
  • Please explain, do you want an array of integers (as your code is doing now) or do you want an array of strings? – Steve Dec 20 '16 at 10:35
  • @Steve Can't tell why this is re-opened. Why do you think this not a duplicate of [this](http://stackoverflow.com/questions/829174/is-there-an-easy-way-to-turn-an-int-into-an-array-of-ints-of-each-digit) which is also a duplicate of [this](http://stackoverflow.com/questions/4808612/how-to-split-a-number-into-individual-digits-in-c). I mean after convert converting it to int OP can then convert it to string with the `ToString()` function.... – Programmer Dec 20 '16 at 10:41
  • Well, this is probably a **BorderlIne Duplicate** as [explained by Jeff here](https://stackoverflow.blog/2009/04/handling-duplicate-questions/) and I have chose to reopen following this point _There's often benefit to having multiple subtle variants of a question around, as people tend to ask and search using completely different words, and the better our coverage, the better odds our fellow programmers can find the answer they're looking for_ However I agree that this is really _borderline_ – Steve Dec 20 '16 at 11:03

1 Answers1

3

Because your code fills the array with the ASCII code for the characters of the number variable. You can use LINQ like below:

int[] digits = number.Select(c => Convert.ToInt32(c.ToString())).ToArray();

Or if you want to assign the each number to a string simply:

string[] digits = number.Select(c => c.ToString()).ToArray();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 1
    We also have `double[] digits = number.Select(char.GetNumericValue).ToArray();` or `int[] digits = number.Select(c => (int)char.GetNumericValue(c)).ToArray();`. – Jeppe Stig Nielsen Dec 20 '16 at 12:36