30

I had to split an int "123456" each value of it to an Int[] and i have already a Solution but i dont know is there any better way : My solution was :

public static int[] intToArray(int num){
    String holder = num.ToString();
    int[] numbers = new int[Holder.ToString().Length]; 
    for(int i=0;i<numbers.length;i++){
        numbers[i] = Convert.toInt32(holder.CharAt(i));
    }
    return numbers;
}
Daniel Abou Chleih
  • 2,440
  • 2
  • 19
  • 31
Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
  • @Hans Passant ,i'm pretty sure about the Array Length because the Longest Number i`ll have can be 999996 so 6 is the Highest Length of an array ,and also Performance is not an issue because of that Number Limitation . – Rosmarine Popcorn Jan 04 '11 at 09:42

15 Answers15

31

A simple solution using LINQ

int[] result = yourInt.ToString().Select(o=> Convert.ToInt32(o) - 48 ).ToArray()
Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
  • 1
    +1 It's interesting to note this approach is just the nice side-effect free implementation of the code in the post: many common imperative operations over homogeneous lists have trivial and clean "functional" counter-parts. –  Jan 02 '11 at 21:43
  • However, edge-cases (say, `-12`) should still be taken into account -- even if it's just a documented restriction on the functions domain. The original post does not itself make this restriction. –  Jan 02 '11 at 21:50
  • 13
    This is wrong, check MarkXA's answer below as the above returns the byte codes for the characters instead of the digits themselves. – Ali Feb 06 '19 at 10:58
  • It doesn't work when I use it with a long number – Ali Zedan Mar 04 '21 at 09:03
  • @Ali, finally, I updated the solution to address your concern! – Jahan Zinedine Apr 07 '21 at 09:08
  • Terrible decision, suitable only for a quick solution of the issue. but in production, converting a value to a string and then converting it back to a value is a very big performance hit.. – Евгений Елисеев Feb 04 '22 at 20:53
27

I believe this will be better than converting back and forth. As opposed to JBSnorro´s answer I reverse after converting to an array and therefore avoid IEnumerable´s which I think will contribute to a little bit faster code. This method work for non negative numbers, so 0 will return new int[1] { 0 }.

If it should work for negative numbers, you could do a n = Math.Abs(n) but I don't think that makes sense.

Furthermore, if it should be more performant, I could create the final array to begin with by making a binary-search like combination of if-statements to determine the number of digits.

public static int[] digitArr(int n)
{
    if (n == 0) return new int[1] { 0 };

    var digits = new List<int>();

    for (; n != 0; n /= 10)
        digits.Add(n % 10);

    var arr = digits.ToArray();
    Array.Reverse(arr);
    return arr;
}

Update 2018:

public static int numDigits(int n) {
    if (n < 0) {
        n = (n == Int32.MinValue) ? Int32.MaxValue : -n;
    }
    if (n < 10) return 1;
    if (n < 100) return 2;
    if (n < 1000) return 3;
    if (n < 10000) return 4;
    if (n < 100000) return 5;
    if (n < 1000000) return 6;
    if (n < 10000000) return 7;
    if (n < 100000000) return 8;
    if (n < 1000000000) return 9;
    return 10;
}

public static int[] digitArr2(int n)
{
    var result = new int[numDigits(n)];
    for (int i = result.Length - 1; i >= 0; i--) {
        result[i] = n % 10;
        n /= 10;
    }
    return result;
}
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
  • I had thought about whether I wanted to create an array first, or reverse the list first. But I thought, why not do them at the same time(using the IEnumerable extension methods). I realise this is only a micro-optimalization, since the list won't be long. The other (more important) argument I came up with was elegance. – JBSnorro Jan 02 '11 at 20:45
  • I think your points are perfectly valid :) I just wanted Burim Shala to know why I did as I did and why I think it is better. I see you have updated your answer which is nice :) – Lasse Espeholt Jan 02 '11 at 21:25
  • A better approach to this is really finding the number of digits first (can be done fast) and then construct the array. This would avoid `List` and `Reverse`. – Lasse Espeholt Sep 10 '14 at 04:26
13
int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x);

but if you want to convert it to 1,2,3,4,5:

int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x - 48);
Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83
11

I'd do it like this:

var result = new List<int>();
while (num != 0) {
    result.Insert(0, num % 10);
    num = num / 10;
}
return result.ToArray();

Slightly less performant but possibly more elegant is:

return num.ToString().Select(c => Convert.ToInt32(c.ToString())).ToArray();

Note that these both return 1,2,3,4,5,6 rather than 49,50,51,52,53,54 (i.e. the byte codes for the characters '1','2','3','4','5','6') as your code does. I assume this is the actual intent?

sebu
  • 2,824
  • 1
  • 30
  • 45
MarkXA
  • 4,294
  • 20
  • 22
6

Using conversion from int to string and back probably isn't that fast. I would use the following

public static int[] ToDigitArray(int i)
{
    List<int> result = new List<int>();
    while (i != 0)
    {
        result.Add(i % 10);
        i /= 10;
    }
    return result.Reverse().ToArray();
}

I do have to note that this only works for strictly positive integers.

EDIT:

I came up with an alternative. If performance really is an issue, this will probably be faster, although you can only be sure by checking it yourself for your specific usage and application.

public static int[] ToDigitArray(int n)
{
    int[] result = new int[GetDigitArrayLength(n)];
    for (int i = 0; i < result.Length; i++)
    {
        result[result.Length - i - 1] = n % 10;
        n /= 10;
    }
    return result;
}
private static int GetDigitArrayLength(int n)
{
    if (n == 0)
        return 1;
    return 1 + (int)Math.Log10(n);
}

This works when n is nonnegative.

JBSnorro
  • 6,048
  • 3
  • 41
  • 62
  • 1
    It doesn't work for zero either, it returns an empty array instead of an array with one digit. – Guffa Jan 02 '11 at 20:25
  • @Guffa, I already said that. I said it only works for positive integers, and zero isn't positive. In fact I said it works for Strictly positive integers only, so with the word "strictly" I explicitly stated that case i = 0 doesn't work. – JBSnorro Jan 02 '11 at 20:27
  • change the function GetDigitArrayLength to int digits = 0; do { n /= 10; digits++; } while (n != 0); return digits; – TheJackal Aug 12 '14 at 07:20
  • Well, the results are the same. Of course you may prefer either solution based on secondary motives.... – JBSnorro Aug 12 '14 at 13:43
4

Thanks to ASCII character table. The simple answer using LINQ above yields answer + 48.

Either

int[] result = youtInt.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();

or

int[] result = youtInt.ToString().Select(o => int.Parse(o.ToString())).ToArray();

can be used

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
2

You can do that without converting it to a string and back:

public static int[] intToArray(int num) {
  List<int> numbers = new List<int>();
  do {
    numbers.Insert(0, num % 10);
    num /= 10;
  } while (num > 0);
  return numbers.ToArray();
}

It only works for positive values, of course, but your original code also have that limitation.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
2

I would convert it in the below manner

if (num == 0)  return new int[1] { 0 };           
var digits = new List<int>();
while (num > 0)
{
   digits.Add(num % 10);
   num /= 10;
}
 var arr = digits.ToArray().Reverse().ToArray();

Kunal Relan
  • 279
  • 3
  • 8
1
string DecimalToBase(int iDec, int numbase)
        {
            string strBin = "";
            int[] result = new int[32];
            int MaxBit = 32;
            for(; iDec > 0; iDec/=numbase)
            {
                int rem = iDec % numbase;
                    result[--MaxBit] = rem;
            } 
            for (int i=0;i<result.Length;i++)
                if ((int)result.GetValue(i) >= base10)
                    strBin += cHexa[(int)result.GetValue(i)%base10];
                else
                    strBin += result.GetValue(i);
            strBin = strBin.TrimStart(new char[] {'0'});
            return strBin;
        }
        int BaseToDecimal(string sBase, int numbase)
        {
            int dec = 0;
            int b;
            int iProduct=1;
            string sHexa = "";
            if (numbase > base10)
                for (int i=0;i<cHexa.Length;i++)
                    sHexa += cHexa.GetValue(i).ToString();
            for(int i=sBase.Length-1; i>=0; i--,iProduct *= numbase)
            {
                string sValue = sBase[i].ToString();
                if (sValue.IndexOfAny(cHexa) >=0)
                    b=iHexaNumeric[sHexa.IndexOf(sBase[i])];
                else 
                    b= (int) sBase[i] - asciiDiff;
                dec += (b * iProduct);
            } 
            return dec; 
        }
Obaid
  • 1,407
  • 19
  • 36
Muthu
  • 11
  • 1
1

i had similar requirement .. i took from many good ideas, and added a couple missing pieces .. where many folks weren’t handling zero or negative values. this is what i came up with:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            _n /= 10;
        }
        return digits;
    }

i think this is pretty clean .. although, it is true we're doing a conditional check and several extraneous calculations with each iteration .. while i think they’re nominal in this case, you could optimize a step further this way:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            //digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            digits[(length - i) - 1] = _n % 10;
            _n /= 10;
        }
        if (n < 0)
            digits[0] *= -1;
        return digits;
    }
jared
  • 11
  • 1
1

A slightly more concise way to do MarkXA's one-line version:

int[] result = n.ToString().Select(c => (int)Char.GetNumericValue(c)).ToArray();

GetNumericValue returns the visible number in your char as a double, so if your string is "12345", it will return the doubles 1,2,3,4,5, which can each be cast to an int. Note that using Convert.ToInt32 on a char in C# returns the ASCII code, so you would get 49,50,51,52,53. This can understandably lead to a mistake.

voluntier
  • 330
  • 4
  • 11
0

Here is a Good Solution for Convert Your Integer into Array i.e: int a= 5478 into int[] There is no issue if You Have a String and You want to convert a String into integer Array for example string str=4561; //Convert into
array[0]=4;
array[1]=5;
array[2]=6;
array[3]=7;

Note: The Number of zero (0) in devider are Equal to the Length of input and Set Your Array Length According to Your input length
Now Check the Coding:

         string str=4587;
            int value = Convert.ToInt32(str);
            int[] arr = new int[4];
            int devider = 10000;
            for (int i = 0; i < str.Length; i++)
            {
                int m = 0;
                devider /= 10;
                arr[i] = value / devider;
                m = value / devider;
                value -= (m * devider);
            }
0
 private static int[] ConvertIntToArray(int variable)
        {
            string converter = "" + variable;
            int[] convertedArray = new int[converter.Length];
            for (int i=0; i < convertedArray.Length;i++) //it can be also converter.Length
            {
                convertedArray[i] = int.Parse(converter.Substring(i, 1));
            }
            return convertedArray;
        }

We get int via using method. Then, convert it to string immediately (123456->"123456"). We have a string called converter and carry to int value. Our string have a string.Length, especially same length of int so, we create an array called convertedArray that we have the length, that is converter(string) length. Then, we get in the loop where we are convert the string to int one by one via using string.Substring(i,1), and assign the value convertedArray[i]. Then, return the convertedArray.At the main or any method you can easily call the method.

  • 1
    I would advise you to add some explanation to your code to cover some of those points: Why is it correct? Why are you doing what you're doing? And similar questions – tung Apr 14 '18 at 16:31
0
public static int[] intToArray(int num)
{
    num = Math.Abs(num);
    int length = num.ToString().Length;
    int[] arr = new int[length];
    do
    {
        arr[--length] = num % 10;
        num /= 10;
    } while (num != 0);

    return arr;
}

Dividing by system base (decimal in this case) removes the right most digit, and we get that digit by remainder operator. We keep repeating until we end up with a zero. Each time a digit is removed it will be stored in an array starting from the end of the array and backward to avoid the need of revering the array at the end. The Math.Abs() function is to handle the negative input, also the array is instantiated with the same size as input length.

M.Khalil
  • 1
  • 3
0

Integer or Long to Integer Array C# Convert it to char array and subtract 48.

 public static int[] IntToArray(int value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }

    public static int[] LongToIntArray(long value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }