计算字符串中的多个单词的问题

时间:2014-11-30 23:12:41

标签: vb.net

我需要一些帮助来找出如何处理这个问题。我尝试制作的代码需要两个用户输入的字符串,打开/搜索一个txt文件,并计算这两个字符串被提及的次数。

使用我到目前为止的代码,它没有考虑一行中的多个字符串。对于前者如果我正在寻找" Bob"并且一行有两个Bob实例,它只计算一个实例。这是非常令人费解的,任何帮助将不胜感激。感谢。

 Dim inFile As IO.StreamReader
    Dim String1 As String
    Dim Count1 As Integer
    Dim Count2 As Integer
    Dim Text1 As String = TextBox1.Text.ToUpper
    Dim Text2 As String = TextBox2.Text.ToUpper

    String1.Text = ""
    String2.Text = ""

    If IO.File.Exists("C:\names.txt") Then
        inFile = IO.File.OpenText("C:\names.txt")

        While Not inFile.EndOfStream
            String1 = inFile.ReadLine()

            If String1.ToUpper.Contains(Text1) Then
                Count1 += 1
                If String1.ToUpper.Contains(Text2) Then
                    Count2 += 1
                End If
            End If
        End While
        inFile.Close()
    Else
        MessageBox.Show("xx",
                        "xx",
                        MessageBoxButtons.OK)
    End If


    String1.Text = Count1.ToString
    String2.Text = Count2.ToString
End Sub

1 个答案:

答案 0 :(得分:0)

以下是一个与您的案例相近的示例(您可以使用变量名称对其进行调整)。此外,最好在单独的方法/函数中执行逻辑并从主循环中调用它。

    Dim inputS, upperS,searchArg, upperSearchArg AS String
    Dim pos,howMany As Integer
    pos=0 'initialize the start position
    howMany=0
    searchArg="Bob " 'use a trailing space if you don't want to find bobby
    upperSearchArg=searchArg.ToUpper()
    inputS="Andrew and Bob are nice but bob is weird some times:"
    upperS=inputS.ToUpper()
    Do      
        pos=upperS.IndexOf(upperSearchArg,pos) 'here we use a variable start position
        if (pos > -1) 
            Console.WriteLine("Found one occurence at:" + pos.ToString())
            howMany=howMany+1
            pos=pos+1 'change the start position
        else
            'pos is -1 here
            exit do
        End if
    Loop
    Console.WriteLine("Total Founds:"+howMany.toString())

请注意,上面的代码不会在以“Bob”结尾但没有尾随空白的字符串中找到“Bob”。这应该很容易解决。

还有其他方法可用于匹配多个字符串,例如使用LINQ。