如何从文本文件中读取单词并将其存储在字符串数组中? [英] How to read words from a text file and store them in an string array?
本文介绍了如何从文本文件中读取单词并将其存储在字符串数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从事一个子手项目.我完成了一切.我将单词保留为如下数组;
I am working on an hangman project. I completed everything. I am keeping words as an array such as below;
string[] words = new string[10] { "SCHOOL", "COMPUTER", "BOOK", "STORY", "APPLE", "TRANSPARENT", "MEDITERRANEAN", "CAT", "RABBIT", "RANDOM" };
但是我想从文本文件中读取它们.我搜索并找到了这个.但是,我不能申请我的项目.
But I want to read them from a text file. I searched and found this. However, I cant apply to my project.
{
string line;
// openFileDialog1.Title = "Openfile";
// openFileDialog1.ShowDialog();
// StreamReader rdLine = new StreamReader(openFileDialog1.FileName);
StreamReader rdLine = new StreamReader("C:/cmpe414/2012Fall/iostreamExample/sonuc.txt");
while ((line = rdLine.ReadLine()) != null)
{
MessageBox.Show(line);
textBox3.Text += line + (char)13 + (char)10;
}
rdLine.Close();
}
推荐答案
最简单的方法是在文本文件中每行存储一个单词.
然后,您可以使用一个语句将它们全部读入字符串arry中:
The easiest way is to store your words one per line in your text file.
You can then read them all into a string arry with one statement:
string[] words = File.ReadAllLines(path);
通过最简单的方法是在记事本中创建一个文本文件,将其命名为Hangman_Words.txt,每行一个单词,例如
By far the simplest way to do this would be to create a text file in Notepad, lets call it Hangman_Words.txt, with one word per line, e.g.
SCHOOL
COMPUTER
BOOK
etc...
然后使用File.ReadAllLines方法将文件直接读取到字符串数组中.
and then read the file directly into a string array using the File.ReadAllLines method.
string[] words = System.IO.File.ReadAllLines("c:\dir\Hangman_Words.txt");
就是这样.
[EDIT},您会发现我和OriginalGriff完全同意.
艾伦.
That''s it really.
[EDIT} and you see that OriginalGriff and I are in complete agreement.
Alan.
这篇关于如何从文本文件中读取单词并将其存储在字符串数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文