我怎么能文本文件转换成int数组列表 [英] how i can convert text file into list of int array
本文介绍了我怎么能文本文件转换成int数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含以下内容的文本文件:
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文件中读取这些整数和int数组列表保存在C#道道任何人的帮助。
解决方案
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
:使用System.IO;
命名空间FileToIntList
{
类节目
{
静态无效的主要(字串[] args)
{
//读取该文件作为一个字符串。
就是System.IO.StreamReader MYFILE =
新就是System.IO.StreamReader(C:\\Users\\M.M.S.I\\Desktop\\test.txt);
串的myString = myFile.ReadToEnd();
myFile.Close();
//显示文件内容。
//Console.WriteLine(myString);
字符RC =(char)10与;
的String [] = listLines myString.Split(RC);
名单,LT;名单< INT>> listArrays =新的List<名单,LT; INT>>();
的for(int i = 0; I< listLines.Length;我++)
{
名单,LT; INT>阵列=新的List< INT>();
的String [] = listInts listLines [I] .Split('');
为(INT J = 0; J< listInts.Length; J ++)
{
如果(listInts [J] =\r!)
{
array.Add(Convert.ToInt32(listInts [J]));
}
}
listArrays.Add(数组);
}
的foreach(列表< INT>数组中listArrays){
的foreach(INT我在阵列)
{
控制台。写入第(i +);
}
Console.WriteLine();
}
到Console.ReadLine();
}
}
}
I have a text file containing the following content:
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
There are no spaces between two rows but there is a space between the numbers. I want to read these integers from a txt file and save in list of int array in C#.Cn anyone help
解决方案
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();
}
}
}
这篇关于我怎么能文本文件转换成int数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文