2017 年 VB 中的单词和元音计数

Word and vowel count in VB 2017

我需要编写一个简单的控制台应用程序,它接受一个输入字符串,然后调用一个子例程来计算字符串中的单词数量和元音字母数量。我写了这篇文章,但出于某种原因,它没有输出我在 Console.Writeline 代码中输入的文本。关于如何执行此操作的任何帮助?

Module Module1

    Sub Main()
        Dim Sentence As String
        Console.WriteLine("Sentence Analysis")
        Console.WriteLine()
        Console.WriteLine("Enter a sentence then press 'Enter'")
        Console.WriteLine()
        Sentence = Console.ReadLine()
        Sentence = Sentence.ToUpper
        Call Words(Sentence)
        Call Vowels(Sentence)
        Console.ReadLine()
    End Sub

    Sub Words(ByVal Input As String)
        Dim Count As Integer
        Dim Index As Short
        Dim Character As Char
        Do Until Index = Len(Input)
            Character = Input.Substring(Index)
            If Character = " " Then
                Count = Count + 1
            End If
        Loop
        Console.WriteLine("Your sentence contains {0} words.", (Count))
    End Sub

    Sub Vowels(ByVal Input As String)
        Dim Count As Integer
        Dim Vowels() As String = {"A", "E", "I", "O", "U"}
        Dim Index As Short
        Dim Character As Char
        Do Until Index = Len(Input)
            Character = Input.Substring(Index)
            If Character = Vowels(Index) Then
                Count = +1
            End If
        Loop
        Console.WriteLine("Your sentence contains {0} words.", (Count))
    End Sub
End Module

Words 中您有以下代码:

Do Until Index = Len(Input)

索引永远不会递增,因此会无限循环。

Vowels 中也有同样的问题

以下对您有帮助吗?

与其查看句子是否包含元音,不如查看元音列表是否包含句子中的每个字符。

对于单词计数,它同样询问包含单个 space 的字符串是否包含句子中的每个字符(本例中的 "word count" 只是 space 的计数s,因此前导或尾随 spaces,或单词之间额外的 spaces,将被计为额外单词,正如您的代码当前所做的那样)。

它还允许我们取消单独的方法调用和手动循环代码,如您所见,这些代码容易出现小错误(我个人建议使用 For 循环而不是在这种情况下比 Do Until 循环,因为 For 循环被设计为自动增加索引)。

Sub Main()
    Console.WriteLine("Sentence Analysis")
    Console.WriteLine()
    Console.WriteLine("Enter a sentence then press 'Enter'")
    Console.WriteLine()

    Dim sentence As String
    sentence = Console.ReadLine()

    Dim vowel_count As Integer = sentence.Count(Function(c) "aeiou".Contains(Char.ToLower(c)))
    Dim word_count As Integer = sentence.Count(Function(c) " ".Contains(Char.ToLower(c)))

    Console.WriteLine("Your sentence contains {0} words.", word_count)
    Console.WriteLine("Your sentence contains {0} vowels.", vowel_count)        

    Console.ReadLine()
End Sub