在visual basic中保存单词列表

时间:2016-10-13 09:19:14

标签: vb.net visual-studio vb.net-2010

如何创建一个程序来识别句子中的单个单词并将它们存储在列表中?我想让程序为该列表中的单词创建一个位置列表,将这些列表保存为单个文件。

模块模块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

结束模块

1 个答案:

答案 0 :(得分: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将其写入文件。