By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,326 Members | 838 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,326 IT Pros & Developers. It's quick & easy.

how many times a word is in a text file

P: 16
i want to find how many time a specified word from a textbox , is in a file text.
this is my code but its not enough because i want to split all the file text to find how time is that word in the file.please help me!


Expand|Select|Wrap|Line Numbers
  1. Imports System.IO
  2. Public Class Form1
  3. Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
  4.         Dim streamreader As System.IO.StreamReader
  5.         Dim nr_fjales As Integer
  6.         nr_fjales = 0
  7.         Dim i As Integer
  8.         streamreader = File.OpenText("C:\Users\user\Desktop\file.txt")
  9.         Dim cont As String
  10.         cont = streamreader.ReadToEnd.Split(" ").ToString
  11.         For i = 0 To streamreader.EndOfStream
  12.             If TextBox1.Text = cont Then
  13.                 nr_fjales = nr_fjales + 1
  14.             End If
  15.         Next
  16.  
  17.         Label2.Text = nr_fjales
  18.  
  19.         streamreader.Close()
  20.  
  21.     End Sub
  22. End Class
Mar 9 '13 #1
Share this Question
Share on Google+
6 Replies


Rabbit
Expert Mod 10K+
P: 12,382
In your loop, it makes no sense to loop to streamreader.EndOfStream. You should loop through each element in your cont array.
Mar 10 '13 #2

P: 16
i never worked with files and i dont know well the sintax, pls do you have any solution
Mar 10 '13 #3

Mikkeee
P: 94
Regular expressions are the way to go. Single line of code will get you what you need. Find the number of matches using RegEx.Matches(exp,matchterm).Count.
Mar 10 '13 #4

P: 16
thanks a lot ,, i understood it a bit .. but can u help me with the code how to link it with the file?
Mar 10 '13 #5

Mikkeee
P: 94
RegEx is super powerful for stuff like this. Read a few tutorials and it will really get you out of a bind.
Expand|Select|Wrap|Line Numbers
  1.         Dim contents As String = System.IO.File.ReadAllText("C:\Users\user\Desktop\file.txt")
  2.         Dim count As Integer = Regex.Matches(contents, TextBox1.Text).Count
  3.         MessageBox.Show(count)
  4.  
Mar 11 '13 #6

P: 16
thanks a lot ,, you are nr1 :)
Mar 11 '13 #7

Post your reply

Sign in to post your reply or Sign up for a free account.