从c#中的文本文件中读取整数
我有一个包含以下内容的文本文件:
0 12 1 15 2 6 3 4 4 3 5 6 6 12 7 8 8 8 9 9 10 13
两行之间没有空格,但两个数字之间有空格。 我想从txt文件中读取这些整数,并将这两列保存到C#中的两个不同的数组中。任何人都可以帮忙
请尝试以下方法:
var r = File.ReadAllLines(path) .Select(line => line.Split(' ')) .Select(arr => new { Column0 = Int32.Parse(arr[0]), Column1 = Int32.Parse(arr[1]) // etc }) .ToArray();
然后:
int[] column0 = r.Select(x => x.Column0).ToArray(); // note double loop over r int[] column1 = r.Select(x => x.Column1).ToArray();
或更长但更有效:
int[] column0 = new int[r.Length], column1 = new int[r.Length]; for (int i = 0; i < r.Length; i++) // single loop over r { column0[i] = t[i].Column0; column1[i] = t[i].Column1; }
甚至更长,但也更有效(一般来说):
List column0 = new List (), column1 = new List (); using (Stream stream = File.Open(path, FileMode.Open)) using (TextReader sr = new StreamReader(stream, Encoding.UTF8)) { string line; while ((line = sr.ReadLine()) != null) { string[] arr = line.Split(' '); column0.Add(Int32.Parse(arr[0]); column1.Add(Int32.Parse(arr[1]); } }
迭代/显示结果(基于零索引,即行0,1等):
for (int i = 0; i < column0.Length; i++) { Console.WriteLine("Line {0}: column 0: {1}, column 1: {2}", i, column0[i], column1[i]); }
为了更好的可靠性,使用函数而不是Int32.Parse:
static int Parse(string input) { int i; if (!Int32.TryParse(intput, out i) throw new Exception("Can't parse " + input); return i; }
您也可以查看以下代码。
上述就是C#学习教程:从c#中的文本文件中读取整数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
string data = string.Empty; List intarray = new List(); void ReadData() { data = File.ReadAllText("Input.txt"); } List Getdata() { string[] lines = data.Split('n', 'r'); foreach (string line in lines) { if(!string.IsNullOrEmpty(line.Trim())) { int[] intdata = new int[2]; string[] d = line.Split(' '); intdata[0] = Convert.ToInt32(d[0]); intdata[1] = Convert.ToInt32(d[1]); intarray.Add(intdata); intdata = null; } } return intarray; }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/959356.html