Word Count in .NET

Ever needed a handy ability to count words in a string using .NET? You are in the right place. There are many ways to count words but I’ll be giving you the most efficient method to do it.

Words can be counted using regular expressions. You can use them for other functionality also. Without further ado, here’s the code:

Private Function CountWord(sampleText As String) As Integer
  Dim words As New System.Text.RegularExpressions.Regex("\S+")
  Dim count As Integer = words.Matches(sampleText).Count
  Return count
End Function

Explanation: Above I have declared a function that can be used anywhere to count the number of words. The first line of the function declares a new Regex object ready to count words. The text in the parenthesis is the regular expression that represents any single word in a string. You can read more about regular expressions here. The second line declares a count variable that holds the number of words. The expression after the declaration of the count variable is the one that does the actual work. The Matches() method returns a collection of matches that were found. In this case, they are the words. The Count is a property which returns the number of matches.

So that’s it. Just add this function, pass a string to it and it will return the word count. If in doubt, use the comments section below. Peace.


Your Thoughts -

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s