2015-10-13 58 views
0

如何制作(列表单词)中的单词列表并用方法填充它void void void ReadWords(string,List。此方法必须获取文件的名称:文本和列表必须用此文件中的话如何使用streamreader从外部文件填充列表

那么,如何做到这一点

我开始用这样的:?

List<string> woorden = new List<string>(); 

// Read the file and display it line by line. 
System.IO.StreamReader file = new System.IO.StreamReader("txt.txt"); 

int counter = 0; 

while (!file.EndOfStream) 
{ 
    string woord = file.ReadLine(); 

    for (int i = 0; i < woord.Length; i++) 
      counter++; 

} 
Console.WriteLine(counter); 
file.Close(); 
Console.ReadKey(); 
+0

你的问题不是很清楚......你需要什么?你卡在哪里? –

回答

1

所以你需要做的是采取来自文件的一行,以及如何将每个单词分开,然后将其添加到列表中,我添加了一些相关的代码下面。

List<string> woorden = new List<string>(); 

// Read the file and display it line by line. 
System.IO.StreamReader file = new System.IO.StreamReader("txt.txt"); 
while (!file.EndOfStream) 
{ 
    string woord = file.ReadLine(); 
    string[] words = woord.Split(' ') //This will take the line grabbed from the file and split the string at each space. Then it will add it to the array 
    for (int i = 0; i < words.Count; i++) //loops through each element of the array 
    { 
     woorden.Add(words[i]); //Add each word on the array on to woorden list 
    } 
} 
Console.WriteLine(); 
file.Close(); 
Console.ReadKey();