2015-10-13 57 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();