So I'm making a small history test to help me study. Currently I have hard coded the array, this is how I want to read in the array from the text file. I want to change this so that i can add and remove dates and events by changing a text file
所以我正在做一个小历史测试来帮助我学习。目前我对数组进行了硬编码,这就是我想从文本文件中读取数组的方法。我想更改此设置,以便我可以通过更改文本文件来添加和删除日期和事件
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
}
The array is merely a place holder for what should be read into from a text file. I know I should use a StreamReader and then split it, but I'm not sure how to do it. I have tried using 2 lists then pushing them onto the array like this
该数组仅仅是应该从文本文件中读取内容的占位符。我知道我应该使用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];
}
This is an example of how the txt file is set out:
这是如何设置txt文件的示例:
1870, Franco-Prussian War (France Defeated),
1870年,法国 - 普鲁士战争(法国击败),
1871, German Empire merges,
1871年,德意志帝国合并,
So you can probably tell, the text file is set out almost identically to the array. So my question is, how would I read in this text file into a 2d array of this format
所以你可以说,文本文件几乎与数组相同。所以我的问题是,如何将此文本文件读入此格式的二维数组中
2 个解决方案
#1
1
The biggest problem here is that you're trying to do this with an array. Unless your program knows how many lines there are at the start, it won't know how big to make the array. You'll either have to guess (error-prone at worst and inefficient at best) or else scan the file for how many line breaks there are (also inefficient).
这里最大的问题是你试图用数组做这个。除非你的程序在开始时知道有多少行,否则它不知道有多大的数组。你要么必须猜测(在最坏的情况下容易出错,最好是效率低下),要么扫描文件中有多少个换行符(效率也很低)。
Just use a List and add each line that you've read to the list.
只需使用List并将您读过的每一行添加到列表中。
Something like the following would parse the file you mention just fine, if there are no commas in the second part of each entry:
如果在每个条目的第二部分中没有逗号,则类似下面的内容将解析您提到的文件就好了:
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 );
}
}
Once you have your list, do whatever you want with it. List members can be accessed exactly like arrays. The main difference is that a list is a dynamically-sized object, whereas an array is stuck at the size you originally make it.
获得清单后,随心所欲。列表成员可以像数组一样访问。主要区别在于列表是动态大小的对象,而数组则以您最初创建的大小为单位。
The list will be an exact replica of your text file, minus the comma, with the dates in the 1st element of each string array and the text in the 2nd element.
该列表将是文本文件的精确副本,减去逗号,每个字符串数组的第一个元素中的日期和第二个元素中的文本。
This would output your original file back to the screen, commas and all:
这会将原始文件输出回屏幕,逗号和所有:
foreach ( string[ ] entry in entries )
{
Console.WriteLine( string.Join( ",", entry ) );
}
If you wanted to get a random element from the array (you said this is a study program), then you could do something like this:
如果你想从数组中获取一个随机元素(你说这是一个学习程序),那么你可以这样做:
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...");
}
#2
0
This should do it for you. Read all lines from the file, then split on the comma and store it in an array.
这应该为你做。从文件中读取所有行,然后在逗号上拆分并将其存储在数组中。
//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
If you need to access the first record, you can do so like this:
如果您需要访问第一条记录,可以这样做:
var firstYear = events[0][0];
var firstDescription = events[0][1];
Breaking it down...
打破它......
-
ReadAllLines
simply opens a file, reads the contents into an array, and closes it.ReadAllLines只是打开一个文件,将内容读入一个数组,然后关闭它。
-
The LINQ statement:
LINQ声明:
- iterates over each line that's not blank
- 迭代不是空白的每一行
- splits each line on the comma and creates a temp variable (pieces) to store the current line in
- 拆分逗号上的每一行并创建一个临时变量(片段)来存储当前行
- stores the contents of the split line in an array
- 将分割线的内容存储在数组中
- does this for each line, and stores the final results in a list - so you have a list of arrays
- 为每一行执行此操作,并将最终结果存储在列表中 - 因此您有一个数组列表
#1
1
The biggest problem here is that you're trying to do this with an array. Unless your program knows how many lines there are at the start, it won't know how big to make the array. You'll either have to guess (error-prone at worst and inefficient at best) or else scan the file for how many line breaks there are (also inefficient).
这里最大的问题是你试图用数组做这个。除非你的程序在开始时知道有多少行,否则它不知道有多大的数组。你要么必须猜测(在最坏的情况下容易出错,最好是效率低下),要么扫描文件中有多少个换行符(效率也很低)。
Just use a List and add each line that you've read to the list.
只需使用List并将您读过的每一行添加到列表中。
Something like the following would parse the file you mention just fine, if there are no commas in the second part of each entry:
如果在每个条目的第二部分中没有逗号,则类似下面的内容将解析您提到的文件就好了:
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 );
}
}
Once you have your list, do whatever you want with it. List members can be accessed exactly like arrays. The main difference is that a list is a dynamically-sized object, whereas an array is stuck at the size you originally make it.
获得清单后,随心所欲。列表成员可以像数组一样访问。主要区别在于列表是动态大小的对象,而数组则以您最初创建的大小为单位。
The list will be an exact replica of your text file, minus the comma, with the dates in the 1st element of each string array and the text in the 2nd element.
该列表将是文本文件的精确副本,减去逗号,每个字符串数组的第一个元素中的日期和第二个元素中的文本。
This would output your original file back to the screen, commas and all:
这会将原始文件输出回屏幕,逗号和所有:
foreach ( string[ ] entry in entries )
{
Console.WriteLine( string.Join( ",", entry ) );
}
If you wanted to get a random element from the array (you said this is a study program), then you could do something like this:
如果你想从数组中获取一个随机元素(你说这是一个学习程序),那么你可以这样做:
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...");
}
#2
0
This should do it for you. Read all lines from the file, then split on the comma and store it in an array.
这应该为你做。从文件中读取所有行,然后在逗号上拆分并将其存储在数组中。
//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
If you need to access the first record, you can do so like this:
如果您需要访问第一条记录,可以这样做:
var firstYear = events[0][0];
var firstDescription = events[0][1];
Breaking it down...
打破它......
-
ReadAllLines
simply opens a file, reads the contents into an array, and closes it.ReadAllLines只是打开一个文件,将内容读入一个数组,然后关闭它。
-
The LINQ statement:
LINQ声明:
- iterates over each line that's not blank
- 迭代不是空白的每一行
- splits each line on the comma and creates a temp variable (pieces) to store the current line in
- 拆分逗号上的每一行并创建一个临时变量(片段)来存储当前行
- stores the contents of the split line in an array
- 将分割线的内容存储在数组中
- does this for each line, and stores the final results in a list - so you have a list of arrays
- 为每一行执行此操作,并将最终结果存储在列表中 - 因此您有一个数组列表