2016-10-13 53 views
0

如何創建一個程序來識別句子中的單個單詞並將它們存儲在列表中?然後,我想讓程序爲該列表中的單詞創建位置列表,將這些列表保存爲單個文件。保存視覺基本單詞列表

模塊模塊1

Sub Main() 
    Dim WordNumber As Integer = 0 
    Dim StartofWord As Integer = 1 
    Dim Text As String = "" 
    Dim L As Integer = 0 
    Dim Word As String 

    Console.WriteLine("Enter your sentence ") 
    Dim LotsofText As String = UCase(Console.ReadLine) 

    Console.WriteLine("Enter your word") 
    Word = UCase(Console.ReadLine()) 


    If Mid(LotsofText, Len(LotsofText) - 1, 1) <> " " Then LotsofText = LotsofText + " " 


    For L = 1 To LotsofText.Length 
     If (Mid(LotsofText, L, 1)) = " " Then 
      WordNumber = WordNumber + 1 
      Text = (Mid(LotsofText, StartofWord, L - StartofWord)) 
      'Console.WriteLine(Text) 
      StartofWord = L + 1 

      If Text = Word Then 
       Console.WriteLine(WordNumber) 

      End If 


     End If 

    Next 


    If Not Text = Word Then 
     Console.WriteLine("Error word not found") 

    End If 


    Console.Write("Press Enter to Exit") 
    Console.ReadLine() 


End Sub 

前端模塊

+0

想想你可能正在尋找Linq。看看http://stackoverflow.com/questions/9645326/how-to-get-distinct-values-from-listof-t-using-linq – Bugs

+1

什麼定義在你的上下文中的「單詞」?如果它只是用空格分隔,你可以使用'String.Split'來獲得一個單詞數組 – simonalexander2005

回答

0

Split你的句子用空" ",遍歷所有單詞和位置添加到列表中,如果當前詞搜索詞匹配。

Dim Sentence = "Hello from the other side and hello from hell" 
Dim SearchWord = "Hello" 

If Not String.IsNullOrWhiteSpace(Sentence) Then 
    SearchWord = SearchWord.Trim 
    Sentence = Sentence.Trim 
    Dim words = Sentence.Split(" ") 
    If Not words.Contains(SearchWord) Then Return 

    Dim searchWordPositions = New List(Of Integer) 
    For i = 0 To words.Length - 1 
     If words(i).Equals(SearchWord, StringComparison.InvariantCultureIgnoreCase) Then 
      searchWordPositions.Add(i) 
     End If 
    Next 
    Console.WriteLine(String.Concat("Found '", SearchWord, "' at Positions: ", String.Join(", ", searchWordPositions))) 
End If 

'Output: 
Found 'Hello' at Positions: 0, 6 

而不是Console.WriteLine將其寫入文件。