如何识别单词在给定文本中出现的位置?

How to indentify the positions that a word occurs in a given text?

我正在开发一个程序,您可以在其中输入一个句子然后搜索一个词。然后程序会告诉你这个词出现在哪些位置。我已经写了一些代码,但不知道如何继续。

Module Module1


Sub Main()
    Dim Sentence As String
    Dim SentenceLength As Integer
    Dim L As Integer = 0
    Dim LotsofText As String = Console.ReadLine


    Console.WriteLine("Enter your word ") : Sentence = Console.ReadLine


    For L = 1 To LotsofText.Length
        If (Mid(LotsofText, L, 1)) = " " Then
        End If
        L = L + 1


        Dim TextCounter As Integer = 0
        Dim MainWord As String = Sentence
        Dim CountChar As String = " "
        Do While InStr(MainWord, CountChar) > 0
            MainWord = Mid(MainWord, 1 + InStr(MainWord, CountChar), Len(MainWord))
            TextCounter = TextCounter + 1

            'Text = TextCounter + 2
            ' Console.WriteLine(Text)

        Loop


        Console.WriteLine(TextCounter)


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


End Sub


End Module

将这段代码从 C# 转换为 Visual Basic。 match.Index 将指示给定单词的位置。

var rx = new Regex("your");
foreach (Match match in rx.Matches("This is your text! This is your text!"))
{
    int i = match.Index;
}

只查找单词而不查找子字符串(例如忽略 "catty" 中的 "cat"):

    Dim LotsofText = "catty cat"
    Dim Sentence = "cat"

    Dim pattern = "\b" & Regex.Escape(Sentence) & "\b"
    Dim matches = Regex.Matches(LotsofText, pattern)

    For Each m As Match In matches
        Debug.Print(m.Index & "") ' 6
    Next

如果您也想查找子字符串,可以删除 "\b" 部分。

如果您将此函数添加到您的代码中:

Public Function GetIndexes(ByVal SearchWithinThis As String, ByVal SearchForThis As String) As List(Of Integer)
    Dim Result As New List(Of Integer)

    Dim i As Integer = SearchWithinThis.IndexOf(SearchForThis)

    While (i <> -1)
        Result.Add(i)
        i = SearchWithinThis.IndexOf(SearchForThis, i + 1)
    End While

    Return Result
End Function

并在您的代码中调用函数:

Dim Indexes as list(of Integer) = GetIndexes(LotsofText, Sentence)

现在 GetIndexes 将在句子中找到您正在搜索的单词的所有索引,并将它们放入列表 Indexes 中。