count a word in .txt file

Talk2Tom11

Well-known member
Joined
Feb 22, 2004
Messages
144
Location
Westchester, NY
I want to count how many times a word exists in a .txt file.

for example i want to open a .txt file and count how many times it ahs the word "Hello" in it, and then display that number in a txtbox on my form.

if anyone can help please post.
 
Only approach I can think of is looping with IndexOf:

Code:
Function CountWord(ByVal strText As String, ByVal strWord As String) As Integer
        Dim i As Integer
        Dim c As Integer = 0
        i = strText.IndexOf(strWord)
        While i > -1
            c = c + 1
            i = strText.IndexOf(strWord, i + 1)
        End While
        Return c
    End Function

:)
 
I think that regex could be pretty handy here. Maybe someone with more regex experience could help you, because my regex experience is very limited. You might want to check it out in the object browser and MSDN.
 
What you could do is read the whole textfile into a string using ReadToEnd.
S = SR.ReadToEnd

At this point you can use any text occurence algorithm to count the words.

For instance, you can use Replace to replace all occurences of "Hello" with "
 
Back
Top