如何使用Visual Basic计算单词出现的次数?

时间:2016-09-29 09:27:10

标签: vb.net

我刚刚开始使用visual basic,想要创建一个计算单词出现次数的程序。我的计划是开发一个程序,分析包含几个没有标点符号的单词的句子。什么时候 该句子中的一个单词被输入,该程序识别该单词出现在句子中的所有位置。

我开始制作一个代码,用来计算句子中的空格数量,但现在卡住了。

Module Module1

    Sub Main()
        Dim Sentence As String
        Dim SentenceLength As Integer
        Dim Text As String
        Console.WriteLine("ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY")

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

        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

2 个答案:

答案 0 :(得分:2)

快速& dirty方法是将字符串拆分为字符串数组,然后计算单词出现在其中的次数:

Dim words() As String = Sentence.Split(new char() {" ", ",", ".", ";"} ' add other punctuation as appropriate 
Dim count = words.Count(Function(word) word = MainWord)

每次遇到空格时,都会使用String.Split方法拆分字符串。然后,它使用Enumerable.Count扩展方法计算匹配特定条件的单词,该单词等于MainWord

答案 1 :(得分:0)

计算子串:

void Update()
{
    PlayerPrefs.SetInt("boomerangbutton", buttonCount);
    PlayerPrefs.Save();
}

计算单词:

Dim count = UBound(Split("catty cat", "cat")) ' 2