2010-06-21 184 views
11

將c#中int數組[1,2,3]中的字符串數組[[1,2,3]]轉換爲最快的方法?將字符串[]轉換爲int []

謝謝

+2

是肯定的項目僅在字符串格式的整數? – 2010-06-21 09:43:10

+0

是的,只有整數 – 2010-06-21 09:43:55

+0

查看http://stackoverflow.com/questions/1297231/convert-string-to-int-in-one-string-of-code-using-linq – abatishchev 2010-06-21 09:49:32

回答

13
var values = new string[] { "1", "2", "3" }; 
values.Select(x => Int32.Parse(x)).ToArray(); 
+1

Int32.TryParse是更快的Int32.Parse – 2010-06-21 10:00:10

+1

而這實際上並沒有給一個數組......並且不是填充這樣一個數組的「最快」(問題)方式。但除此之外...... – 2010-06-21 10:02:51

+1

a)它返回的數據結構與您要求的不同,b)Marc Gravell的答案比其他人在這裏的答案要好一個數量級? – 2010-06-21 10:02:59

1

迭代和轉換。

1

的比較是我知道有沒有快速的方式,但你可以用一個「短的路「:

var numbers = new[] {"1", "2", "3"}; 

var result = numbers.Select(s => int.Parse(s)); 
int[] resultAsArray = result.ToArray(); 

如果你使用PLINK,你可以並行計算值。

22
string[] arr1 = {"1","2","3"}; 
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s)); 

採用Array.ConvertAll確保(不同於LINQ Select/ToArray),該陣列是在合適大小初始化。你可以儘可能獲得遮陽更快的展開,但並不多:

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

如果你需要的東西更快還是(或許是大容量文件/數據處理),然後寫自己的解析可以幫助;內置的處理很多的邊緣情況 - 如果你的數據更簡單,你真的可以減少這一點。


另一種可選擇的解析器的例子:

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; 
       } 
     } 
    } 
+1

關於ConvertAll的有趣點,不知道! – 2010-06-21 09:53:19

2

我可能會做的事:

string[] array = new[] { "1", "2" }; // etc. 
int[] ints = array.Select(x => int.Parse(x)).ToArray(); 

如果我能保證數據將只有整數。

如果不是:

string[] array = new[] { "1", "2" }; // etc. 
List<int> temp = new List<int>(); 
foreach (string item in array) 
{ 
    int parsed; 
    if (!int.TryParse(item, out parsed)) 
    { 
     continue; 
    } 

    temp.Add(parsed); 
} 

int[] ints = temp.ToArray(); 
1
string[] arr = new string[]{ "1", "2", "3" }; 
int[] lss = (from xx in arr 
      select Convert.ToInt32(xx)).ToArray();