Converting integer into array of single digits in C#?

  • Context: C# 
  • Thread starter Thread starter rollcast
  • Start date Start date
  • Tags Tags
    Array Integer
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 60K views
rollcast
Messages
403
Reaction score
0
Whats the easiest way to take an integer in C# and convert it into an array of length equal to the number of digits and each element is a digit from the integer?

EG. If I had the integer 12345 I want to convert it to an array like so {1, 2, 3, 4, 5}

Thanks
AL
 
Physics news on Phys.org
rollcast said:
Whats the easiest way to take an integer in C# and convert it into an array of length equal to the number of digits and each element is a digit from the integer?

EG. If I had the integer 12345 I want to convert it to an array like so {1, 2, 3, 4, 5}

Thanks
AL

I don't know if it's easiest, but in C I would use the modulus operator %. Can you see how you would use it to do this task?
 
berkeman said:
I don't know if it's easiest, but in C I would use the modulus operator %. Can you see how you would use it to do this task?

Nope, :confused:
 
Converting 12345 to an integer array:

Code:
int[] digits = 12345.ToString().ToCharArray().Select(Convert.ToInt32).ToArray();

If you only need a character array you can obviously stop after the ToCharArray().
 
Filip Larsen said:
Converting 12345 to an integer array:

Code:
int[] digits = 12345.ToString().ToCharArray().Select(Convert.ToInt32).ToArray();

If you only need a character array you can obviously stop after the ToCharArray().

The conversion to an int array is not quite right. The Convert.ToInt32 will convert the char to its equivalent decimal value which is not the same as parsing it. e.g. the character '1' will be converted to 49. Instead you will have to use the int.Parse which will require casting the char to a string first but the better approach is to use the Char.GetNumericValue and cast to int16, int32 as preferred because the method returns a double.

The code should look like:


Code:
int[] digits = 12345.ToString().ToCharArray().Select(x => (int)Char.GetNumericValue(x)).ToArray();

To take it to the next level and you want to convert an unknown string you can use regex to strip out non numeric characters.

Code:
int[] digits = Regex.Replace(numberToParse, "[^0-9]", "").Select(x => (int)Char.GetNumericValue(x)).ToArray();