0

我想读取一个文本文件并相互删减单词,例如这是我的文本文件:

asd
asdc
asf
气体
asdf

现在我想读“asd”,然后是“asdc”,然后是“asf”……我该怎么做?

4

2 回答 2

0
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);
}

此代码逐行读取文本文件并将每一行分隔为单词(按空格和制表符)。您必须自己处理异常。

于 2013-01-18T11:41:18.140 回答
0

使用 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);
    }
}

}

于 2013-01-18T11:41:39.187 回答