我有一个包含以下内容的文本文件:
0 0 1 0 3
0 0 1 1 3
0 0 1 2 3
0 0 3 0 1
0 0 0 1 2 1 1
0 0 1 0 3
0 0 1 1 3
0 0 1 2 3
0 0 3 0 1
0 0 1 2 3
0 0 3 0 1
行之间没有空格,但数字之间有空格。我想从txt文件中读取这些整数,并保存在C#中的int数组列表中。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileToIntList
{
class Program
{
static void Main(string[] args)
{
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("C:\\Users\\M.M.S.I\\Desktop\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
//Console.WriteLine(myString);
char rc = (char)10;
String[] listLines = myString.Split(rc);
List<List<int>> listArrays = new List<List<int>>();
for (int i = 0; i < listLines.Length; i++)
{
List<int> array = new List<int>();
String[] listInts = listLines[i].Split(' ');
for(int j=0;j<listInts.Length;j++)
{
if (listInts[j] != "\r")
{
array.Add(Convert.ToInt32(listInts[j]));
}
}
listArrays.Add(array);
}
foreach(List<int> array in listArrays){
foreach (int i in array)
{
Console.Write(i + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句