Fastest way to separate the digits of an int into an array in .NET?

后端 未结 11 788
天涯浪人
天涯浪人 2021-01-31 20:07

I want to separate the digits of an integer, say 12345, into an array of bytes {1,2,3,4,5}, but I want the most performance effective way to do that, because my program does tha

11条回答
  •  余生分开走
    2021-01-31 20:50

    Just for fun, here's a way to separate all the digits using just one C# statement. It works this way: the regular expression uses the string version of the number, splits apart its digits into a string array, and finally the outer ConvertAll method creates an int array from the string array.

        int num = 1234567890;
    
        int [] arrDigits = Array.ConvertAll(
            System.Text.RegularExpressions.Regex.Split(num.ToString(), @"(?!^)(?!$)"),
            str => int.Parse(str)
            );
    
        // resulting array is [1,2,3,4,5,6,7,8,9,0]
    

    Efficiency-wise?... I'm unsure compared to some of the other fast answers I see here. Somebody would have to test it.

提交回复
热议问题