2014-11-03 232 views
2

我被轉換一個字符串數組,一個整數數組

string[] code = System.IO.File.ReadAllLines(@"C:\randoms\randnum.txt"); 

然後我placethis成讀取使用C#.NET V3.5表達2010在格式

18 11 2 18 3 14 1 0 1 3 22 15 0 6 8 23 18 1 3 4 10 15 24 17 17 16 18 10 17 18 23 17 11 19 

含整數的文本文件一個字符串由

string s1 = Convert.ToString(code); 

而且需要能夠將它讀入int數組進行一些數學處理。

我用盡了一切建議在本網站下關於這個主題的其他職位,包括分析和隱蔽陣列,但一旦我嘗試這個,我得到了可怕的「輸入字符串是不正確的格式」消息

+0

你爲什麼要將字符串[]再次轉換爲字符串? – dotctor 2014-11-03 23:53:19

+0

你將不得不將每個單值轉換爲整數 – Icepickle 2014-11-03 23:53:24

回答

1
var intArray = File.ReadAllText(@"C:\randoms\randnum.txt") 
     .Split((char[]) null, StringSplitOptions.RemoveEmptyEntries) 
     .Select(int.Parse).ToArray(); 
+0

任何投票的理由? – dotctor 2014-11-04 00:21:15

+1

我沒有意識到Split()以null方式工作。我喜歡這個解決方案,因爲它假定每個整數之間有任意數量的空白。 – 2014-11-04 00:34:49

+0

工作出色。謝謝 – 2014-11-04 20:49:48

-1

乍一看,問題在於你用ReadAllLines來讀數。這將返回一個字符串數組,其中每個字符串表示文件中的一行。在你的例子中,你的數字看起來都在一行上。您可以使用System.IO.File.ReadAllText來獲取單個字符串。然後使用.Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries);獲取您要查找的字符串數組。

string allTheText = System.IO.File.ReadAllText(@"C:\randoms\randnum.txt"); 
string[] numbers = allTheText.Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries); 
2

你可以使用LINQ:

var ints = code.SelectMany(s => s.Split(' ')).Select(int.Parse).ToList(); 

這將需要你的空間分隔的數字列表,並將其壓扁成整數

+0

不幸的是,第一次嘗試了這個結果。 – 2014-11-04 20:56:41

1

一些這些答案都是偉大的一維列表,但如果您的文件包含任何不能轉換爲int的字符串,則int.Parse()將引發異常。

雖然稍貴,但可以考慮做一個TryParse。這給你一些例外處理:

int tmp = 0; // Used to hold the int if TryParse succeeds 

int[] intsFromFile = 
    File.ReadAllText(@"C:\randoms\randnum.txt") 
     .Split(null) 
     .Where(i => int.TryParse(i, out tmp)) 
     .Select(i => tmp) 
     .ToArray(); 
+0

OP說:「我正在閱讀使用C#.Net v3.5 express 2010 **的文本文件,其中包含整數**,格式爲」 – dotctor 2014-11-04 00:25:31

+0

「如果文件包含任何分隔符字符(如'\ t'或'\ n'),該怎麼辦?那麼你會放棄一些數字。「文件並非總是與您期望的格式完全一樣」 – dotctor 2014-11-04 00:32:28

+0

我的意思是,如果「文件不總是與您期望的文件格式完全一致」,則不應指望數字僅由空格字符分隔 – dotctor 2014-11-04 00:36:52

0

這是一個單線,真的。這會給你一個整數的一維數組在文件中:

private static rxInteger rxInteger = new Regex(@"-?\d+") ; 

... 

int[] myIntegers1 = rxInteger 
        .Matches(File.ReadAllText(@"C:\foo\bar\bazbat")) 
        .Cast<Match>() 
        .Select(m => int.Parse(m.Value)) 
        .ToArray() 
        ; 

如果你希望它是一個2維衣衫襤褸陣列,這不是要複雜得多:

int[][] myIntegers2 = File 
         .ReadAllLines(@"C:\foo\bar\bazbat") 
         .Select(s => 
         rxInteger 
         .Matches(s) 
         .Cast<Match>() 
         .Select(m => int.Parse(m.Value)) 
         .ToArray() 
        ) 
         .ToArray() 
         ; 

[實施驗證和錯誤處理留給讀者練習]

相關問題