Mike
Mike

Reputation: 1

.NET Counting vowels from a text file

As a newbie to .NET I decided to set myself the little challenge of writing a program to count the number of vowels from an input string. The program below works fine, but then, to develop this further I thought, instead of entering the string via console.readline, would it be possible to extract the text from a text file? I tried using the FileOpen/FileClose and StreamReader approach to resolve this issue with the mind set that the text file should be converted to a CharArray. Am I looking at this problem from completely the wrong angle? Can I customise my existing code and adapt it for text files, or do I need to adopt a completely new approach?

Any help most appreciated, Thanks

Module Module1

Sub Main()
    Dim counter1 As Integer = 0
    Console.WriteLine("Enter a word")
    Dim myWord As String = Console.ReadLine()
    Dim charArray() As Char = myWord.ToCharArray()

    For Each letter In charArray
        Select Case letter
            Case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U"
                counter1 = counter1 + 1
        End Select
    Next
    Console.WriteLine("The number of VOWELS in this word is " & counter1)

    Console.ReadLine()

End Sub
End Module

Upvotes: 0

Views: 653

Answers (2)

rory.ap
rory.ap

Reputation: 35318

You can do this in one line:

Console.WriteLine(Regex.Matches(File.ReadAllText("C:\input.txt"), "[aeiouAEIOU]").Count)

File is in the System.IO namespace, and Regex is in the System.Text.RegularExpressions namespace.

Just a note about this: while it's pretty rad that you can do this in one line, it's not always best to do things like this. I like to keep method calls out in their own statements because it makes it easier to debug when you can see the value returned by each one.

Upvotes: 4

Mark
Mark

Reputation: 8160

Your Select Case check is probably pretty efficient, and can be adapted to count the vowels in a file easily. You can use File.ReadLines to iterate through the lines in a file, and use the Select Case check on each line. This should work even on huge files, since it's not reading the whole file into memory.

Dim count = 0
For Each line In File.ReadLines("C:\BigTextFile.txt")
    For Each c In line
        Select Case c
            Case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U"
                count += 1
        End Select
    Next
Next
Console.WriteLine(count)

Depending on your text file, you may need to specify the encoding.

Upvotes: 1

Related Questions