繁体   English   中英

将文本文件拆分为二维数组

[英]Splitting a text file into a 2d array

因此,我正在做一个小的历史测试以帮助我学习。 目前,我已经对数组进行了硬编码,这就是我想从文本文件中读取数组的方式。 我想更改此设置,以便可以通过更改文本文件来添加和删除日期和事件

static string[,] dates = new string[4, 2]
        {
            {"1870", "France was defeated in the Franco Prussian War"},
            {"1871", "The German Empire Merge into one"},
            {"1905", "The \"Schliffin PLan\" devised"},
            {"1914", "The Assassination of Franz Ferdinand and the start of WW1"},
            //etc
        }

该数组只是占位符,用于应从文本文件读取的内容。 我知道我应该使用StreamReader然后将其拆分,但是我不确定该怎么做。 我试过使用2个列表,然后像这样将它们推入数组

//for date/event alteration
isDate = true;
//for find the length of the file, i don't know a better way of doing this
string[] lineAmount = File.ReadAllLines("test.txt");
using (StreamReader reader = new StreamReader("test.txt"))
                {

                    for (int i = 0; i <= lineAmount.Length; i++)
                    {
                        if (isDate)
                        {
                            //use split here somehow?
                            dates.Add(reader.ReadLine());
                            isDate = false;
                        }
                        else
                        {
                            events.Add(reader.ReadLine());
                            isDate = true;
                        }
                    }
                }


        string[] dates2 = dates.ToArray();
        string[] events2 = events.ToArray();
        string[,] info = new string[,] { };
        //could use dates or events for middle (they have the same amount)
        //push the lists into a 2d array
        for (int i = 0; i <= events2.Length; i++)
        {
            //gives an index out of bounds of array error
            //possibly due to the empty array declaration above? not sure how to fix
            info[0, i] = dates2[i];
            info[1, i] = events2[i];
        }

这是如何列出txt文件的示例:

1870年,法普战争(法国​​大败),

1871年,德意志帝国合并,

因此,您可能会知道,文本文件的设置几乎与数组相同。 所以我的问题是,如何将这个文本文件读入这种格式的二维数组

这里最大的问题是您正在尝试使用数组执行此操作。 除非您的程序知道开始时有多少行,否则它将不知道要制作多大的数组。 您要么不得不猜测(最容易出错的错误,最好是效率低的错误),要么扫描文件以查找有多少个换行符(效率也低)。

只需使用一个列表,然后将已阅读的每一行添加到列表中即可。

如果每个条目的第二部分中没有逗号,则类似以下内容的文件就可以很好地解析您提到的文件:

List<string[ ]> entries = new List<string[ ]>( );
using ( TextReader rdr = File.OpenText( "TextFile1.txt" ) )
{
    string line;
    while ( ( line = rdr.ReadLine( ) ) != null )
    {
        string[ ] entry = line.Split( ',' );
        entries.Add( entry );
    }
}

有了列表后,就可以使用它进行任何操作。 列表成员可以像访问数组一样进行访问。 主要区别在于列表是一个动态大小的对象,而数组则停留在最初的大小上。

该列表将是文本文件的精确副本(减去逗号),日期在每个字符串数组的第一个元素中,文本在第二个元素中。

这会将您的原始文件输出回屏幕,逗号和所有其他内容:

foreach ( string[ ] entry in entries )
{
    Console.WriteLine( string.Join( ",", entry ) );
}

如果您想从数组中获取随机元素(您说这是一个学习程序),则可以执行以下操作:

Random rand = new Random();
while(true)
{
    int itemIndex = rand.Next(0, entries.Length);
    Console.WriteLine( "What year did {0} happen?", entries[itemIndex][1]);
    string answer = Console.ReadLine();
    if(answer == "exit")
        break;
    if(answer == entries[itemIndex][0])
        Console.WriteLine("You got it!");
    else
        Console.WriteLine("You should study more...");
}

这应该为您做。 从文件中读取所有行,然后在逗号上分割并将其存储在数组中。

//Read the entire file into a string array, with each element being one line
//Note that the variable 'file' is of type string[]
var file = File.ReadAllLines(@"C:\somePath.yourFile.txt");

var events = (from line in file  //For every line in the string[] above
              where !String.IsNullOrWhiteSpace(line)   //only consider the items that are not completely blank
              let pieces = line.Split(',')  //Split each item and  store the result into a string[] called pieces
              select new[] { pieces[0], pieces[1].Trim() }).ToList(); //Output the result as a List<string[]>, with the second element trimmed of extra whitespace

如果您需要访问第一条记录,可以这样进行:

var firstYear = events[0][0];
var firstDescription = events[0][1];

分解...

  • ReadAllLines只是打开一个文件,将内容读入数组,然后关闭它。

  • LINQ语句:

    • 遍历每个非空白的行
    • 在逗号上分割每一行,并创建一个临时变量(件)以将当前行存储在
    • 将分割线的内容存储在数组中
    • 为每一行执行此操作,并将最终结果存储在列表中-因此您具有数组列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM