• 0

[VB.NET] Count a specific word in a text document?


Question

5 answers to this question

Recommended Posts

  • 0

EDIT: nvm my first example with a linq expression, it was way too inefficient.

As wrack says, the best way is to use Regex.

Imports System.IO
Imports System.Text.RegularExpressions

Module Module1

	Sub Main()
		Dim text = File.ReadAllText("G:\USER\Documents\MyFile.log")
		Dim count = Regex.Matches(text, "a_word").Count
		Console.WriteLine(count)
		Console.ReadKey()
	End Sub

End Module

This code first stores the contents of MyFile.log as a string in "text". Then it counts the number of occurences of "a_word" in it.

Edited by Dr_Asik
  • 0

Actually, for even better efficiency, you should use a StreamReader instead of File.ReadAllText().

Using tr As TextReader = New StreamReader("G:\USER\Documents\MyFile.log")
	 count = Regex.Matches(tr.ReadToEnd(), "a_word").Count
End Using

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.