Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

Posted

Only approach I can think of is looping with IndexOf:

 

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

 

:)

Please check the Knowledge Base before you post.

"Computers are useless. They can only give you answers." - Pablo Picasso

The Code Net

  • Leaders
Posted
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.
[sIGPIC]e[/sIGPIC]
  • Leaders
Posted

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 "ÿ"

and then Split the newly formed string at "ÿ". This will give you an array of elements in the string... but more importantly, the .GetUpperBound(0) of the array will be equal to the number of occurences of "Hello" in the string.

If you want to find Hello as a word and not as a character sequence (as in "SDVHellovsd" does not find "Hello", then you'd probably want to consider trying to formulate a RegEx expression or doing your own with multiple Replaces...

:)

Iceplug, USN

One of my coworkers thinks that I believe that drawing bullets is the most efficient way of drawing bullets. Whatever!!! :-(

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...