Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Converting integer into array of single digits in C#?

  1. Dec 9, 2011 #1
    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
     
  2. jcsd
  3. Dec 9, 2011 #2

    berkeman

    User Avatar

    Staff: Mentor

    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?
     
  4. Dec 9, 2011 #3
    Nope, :confused:
     
  5. Dec 9, 2011 #4

    Filip Larsen

    User Avatar
    Gold Member

    Converting 12345 to an integer array:

    Code (Text):
    int[] digits = 12345.ToString().ToCharArray().Select(Convert.ToInt32).ToArray();
    If you only need a character array you can obviously stop after the ToCharArray().
     
  6. Sep 19, 2012 #5
    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 (Text):
    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 (Text):
    int[] digits = Regex.Replace(numberToParse, "[^0-9]", "").Select(x => (int)Char.GetNumericValue(x)).ToArray();
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Converting integer into array of single digits in C#?
  1. C++ Array (Replies: 10)

  2. C# arrays (Replies: 1)

Loading...