【问题标题】:How to indentify the positions that a word occurs in a given text?如何识别一个单词在给定文本中出现的位置?
【发布时间】:2017-02-14 23:19:53
【问题描述】:

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

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

【问题讨论】:

  • Mid、Instr 等的存在只是为了与 VB6 和 VBA 兼容。永远不要使用它们。

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


【解决方案1】:

将这段代码从 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;
}

【讨论】:

    【解决方案2】:

    只查找单词而不查找子字符串(例如忽略“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" 部分。

    【讨论】:

      【解决方案3】:

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

      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 将在句子中找到您要搜索的单词的所有索引,并将它们放入索引列表中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-10
        • 2011-07-16
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 2017-10-06
        • 1970-01-01
        • 2022-08-12
        相关资源
        最近更新 更多