[英]Converting a string array to an integer array
我正在使用C#.Net v3.5 Express 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[] code = System.IO.File.ReadAllLines(@"C:\randoms\randnum.txt");
然后我將其放入字符串
string s1 = Convert.ToString(code);
並且需要能夠將其讀入int數組以進行一些數學處理。
我已經嘗試過該站點上關於該主題的其他帖子下建議的所有內容,包括解析和隱蔽數組,但是一旦嘗試執行此操作,我將收到可怕的“輸入字符串格式不正確”消息
var intArray = File.ReadAllText(@"C:\randoms\randnum.txt")
.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
您可以使用LINQ:
var ints = code.SelectMany(s => s.Split(' ')).Select(int.Parse).ToList();
這將把您的以空格分隔的數字列表放到一維整數列表中
其中一些答案很好,但是如果您的文件包含無法轉換為int的任何字符串,則int.Parse()
將引發異常。
雖然稍微貴一點,但考慮改用TryParse。 這為您提供了一些異常處理:
int tmp = 0; // Used to hold the int if TryParse succeeds
int[] intsFromFile = System.IO.File
.ReadAllText(@"C:\randoms\randnum.txt")
.Split(null)
.Where(i => int.TryParse(i, out tmp))
.Select(i => tmp)
.ToArray();
真的,這是單線的。 這將為您提供文件中的一維整數數組:
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()
;
如果您希望它是一個二維的參差不齊的數組,那就不復雜了:
int[][] myIntegers2 = File
.ReadAllLines( @"C:\foo\bar\bazbat" )
.Select( s =>
rxInteger
.Matches(s)
.Cast<Match>()
.Select( m => int.Parse(m.Value) )
.ToArray()
)
.ToArray()
;
[驗證和錯誤處理的實現留給讀者練習]
乍看起來,問題似乎在於您正在使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.