【发布时间】:2013-01-18 11:35:04
【问题描述】:
我想读取一个文本文件并将单词彼此分割,例如这是我的文本文件:
asd
asdc
asf
气体
asdf
现在我想读“asd”,然后是“asdc”,然后是“asf”...... 我该怎么办?
【问题讨论】:
标签: file text dictionary word words
我想读取一个文本文件并将单词彼此分割,例如这是我的文本文件:
asd
asdc
asf
气体
asdf
现在我想读“asd”,然后是“asdc”,然后是“asf”...... 我该怎么办?
【问题讨论】:
标签: file text dictionary word words
使用 StreamReader 的 ReadLine,您可以像这样逐行读取:
使用系统; 使用 System.IO;
类测试 {
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
【讨论】:
List<string> words = new List<string>();
string line;
char[] sep = new char[] { ' ', '\t' };
try
{
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while ((line = file.ReadLine()) != null)
{
words.AddRange(line.Split(sep, StringSplitOptions.RemoveEmptyEntries));
}
file.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
此代码逐行读取文本文件并将每一行分隔为单词(按空格和制表符)。您必须自己处理异常。
【讨论】:
C:\\test.txt 替换为文件路径,结果将作为字符串列表包含在words 变量中:)。