C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Regex pattern: This means each match consists of one or more non-whitespace characters.
Main: We use two String literals as arguments to CountWords. Then we write the word counts that were received.
Result: The first sentence, from Shakespeare's play Hamlet, has ten words. The second sentence, from a nursery rhyme, has five words.
VB.NET program that counts words
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
' Count words in this string.
Dim value As String = "To be or not to be, that is the question."
Dim count1 As Integer = CountWords(value)
' Count words again.
value = "Mary had a little lamb."
Dim count2 As Integer = CountWords(value)
' Display counts.
Console.WriteLine(count1)
Console.WriteLine(count2)
End Sub
''' <summary>
''' Use regular expression to count words.
''' </summary>
Public Function CountWords(ByVal value As String) As Integer
' Count matches.
Dim collection As MatchCollection = Regex.Matches(value, "\S+")
Return collection.Count
End Function
End Module
Output
10
5
Note: The function here was run through a battery of tests against Microsoft Word. It was found to have a difference of 0.022%.
Word Count