Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - convert string[] to int[]

Which is the fastest method for convert an string's array ["1","2","3"] in a int's array [1,2,3] in c#?

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
string[] arr1 = {"1","2","3"};
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s));

The use of Array.ConvertAll ensures (unlike LINQ Select/ToArray) that the array is initialized at the right size. You can possible get a shade quicker by unrolling, but not much:

int[] arr2 = new int[arr1.Length];
for(int i = 0 ; i < arr1.Length ; i++) {
    arr2[i] = int.Parse(arr[i]);
}

If you need something faster still (perhaps bulk file/data handling), then writing your own parse might help; the inbuilt one handles a lot of edge-cases - if your data is simpler you really can cut this down a bit.


For an example of an alternative parser:

    public static unsafe int ParseBasicInt32(string s)
    {
        int len = s == null ? 0 : s.Length;
        switch(s.Length)
        {
            case 0:
                throw new ArgumentException("s");
            case 1:
                {
                    char c0 = s[0];
                    if (c0 < '0' || c0 > '9') throw new ArgumentException("s");
                    return c0 - '0';
                }
            case 2:
                {
                    char c0 = s[0], c1 = s[1];
                    if (c0 < '0' || c0 > '9' || c1 < '0' || c1 > '9') throw new ArgumentException("s");
                    return ((c0 - '0') * 10) + (c1 - '0');
                }
            default:
                fixed(char* chars = s)
                {
                    int value = 0;
                    for(int i = 0; i < len ; i++)
                    {
                        char c = chars[i];
                        if (c < '0' || c > '9') throw new ArgumentException("s");
                        value = (value * 10) + (c - '0');
                    }
                    return value;
                }
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...