how many times a word is in a text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thomaaxha
    New Member
    • Mar 2013
    • 16

    how many times a word is in a text file

    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!


    Code:
    Imports System.IO
    Public Class Form1
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim streamreader As System.IO.StreamReader
            Dim nr_fjales As Integer
            nr_fjales = 0
            Dim i As Integer
            streamreader = File.OpenText("C:\Users\user\Desktop\file.txt")
            Dim cont As String
            cont = streamreader.ReadToEnd.Split(" ").ToString
            For i = 0 To streamreader.EndOfStream
                If TextBox1.Text = cont Then
                    nr_fjales = nr_fjales + 1
                End If
            Next
    
            Label2.Text = nr_fjales
    
            streamreader.Close()
    
        End Sub
    End Class
    Last edited by acoder; Mar 9 '13, 10:43 PM. Reason: Please use [code] tags when posting code
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    In your loop, it makes no sense to loop to streamreader.En dOfStream. You should loop through each element in your cont array.

    Comment

    • thomaaxha
      New Member
      • Mar 2013
      • 16

      #3
      i never worked with files and i dont know well the sintax, pls do you have any solution

      Comment

      • Mikkeee
        New Member
        • Feb 2013
        • 94

        #4
        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(e xp,matchterm).C ount.

        Comment

        • thomaaxha
          New Member
          • Mar 2013
          • 16

          #5
          thanks a lot ,, i understood it a bit .. but can u help me with the code how to link it with the file?

          Comment

          • Mikkeee
            New Member
            • Feb 2013
            • 94

            #6
            RegEx is super powerful for stuff like this. Read a few tutorials and it will really get you out of a bind.
            Code:
                    Dim contents As String = System.IO.File.ReadAllText("C:\Users\user\Desktop\file.txt")
                    Dim count As Integer = Regex.Matches(contents, TextBox1.Text).Count
                    MessageBox.Show(count)

            Comment

            • thomaaxha
              New Member
              • Mar 2013
              • 16

              #7
              thanks a lot ,, you are nr1 :)

              Comment

              Working...