Search code examples
vb.netfunctionprocedures

CountWord and CountVowel into Function in VB.NET


Hi I need to change WordCount and CountVowel procedures to functions and create a function to count number of consonants in a string.

I have done these two procedures but I cannot figure out how to do the last part. I am fairly new to programming.

My current code is given below:

Sub Main()
    Dim Sentence As String
    Console.WriteLine("Sentence Analysis" + vbNewLine + "")
    Console.WriteLine("Enter a sentence, then press 'Enter'" + vbNewLine + "")
    Sentence = Console.ReadLine()
    Console.WriteLine("")
    Call WordCount(Sentence)
    Call VowelCount(Sentence)
    Console.ReadLine()
End Sub
Sub WordCount(ByVal UserInput As String)
    Dim Space As String() = UserInput.Split(" ")
    Console.WriteLine("There are {0} words", Space.Length)
End Sub
Sub VowelCount(ByVal UserInput As String)
    Dim i As Integer
    Dim VowelNumber As Integer
    Dim Vowels As String = "aeiou"
    For i = 1 To Len(UserInput)
        If InStr(Vowels, Mid(UserInput, i, 1)) Then
            VowelNumber = VowelNumber + 1
        End If
    Next
    Console.WriteLine("There are {0} vowels", VowelNumber)
End Sub

Thanks for your time


Solution

  • Here you go.

    Function WordCount(ByVal UserInput As String) As Integer
        Dim Space As String() = UserInput.Split(" ")
        Return Space.Length
    End Function
    
    Function VowelCount(ByVal UserInput As String) As Integer
        Dim i As Integer
        Dim VowelNumber As Integer
        Dim Vowels As String = "aeiou"
        For i = 1 To Len(UserInput)
            If InStr(Vowels, Mid(UserInput, i, 1)) Then
                VowelNumber = VowelNumber + 1
            End If
        Next
        Return VowelNumber
    End Function
    
    Function ConsonantCount(ByVal UserInput As String) As Integer
        Dim i As Integer
        Dim ConsonantNumber As Integer
        Dim Consonants As String = "bcdfghjklmnpqrstvwxyz"
        For i = 1 To Len(UserInput)
            If InStr(Consonants, Mid(UserInput, i, 1)) Then
                ConsonantNumber = ConsonantNumber + 1
            End If
        Next
        Return ConsonantNumber
    End Function