Talk2Tom11 Posted September 17, 2005 Posted September 17, 2005 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. Quote
mark007 Posted September 17, 2005 Posted September 17, 2005 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 :) Quote Please check the Knowledge Base before you post. "Computers are useless. They can only give you answers." - Pablo Picasso The Code Net
Leaders snarfblam Posted September 17, 2005 Leaders Posted September 17, 2005 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. Quote [sIGPIC]e[/sIGPIC]
Leaders Iceplug Posted September 17, 2005 Leaders Posted September 17, 2005 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... :) Quote Iceplug, USN One of my coworkers thinks that I believe that drawing bullets is the most efficient way of drawing bullets. Whatever!!! :-(
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.