VB.NET Word Count Function
Dot Net Perls
How can you count words in a String in your VB.NET program? Words are delimited by spaces and some types of punctuation. The easiest way to count words is with a regular expression. In this article, we use a Regex to count the number of words in a String.
Count words
First, this program imports the System.Text.RegularExpressions namespace. This allows us to use the Regex type directly in the CountWords function. In CountWords, we use the Regex.Matches shared function with the pattern "\S+"; this means each match consists of one or more non-whitespace characters.
Program that counts words [VB.NET]
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
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
[本日志由 tiancao1001 于 2012-01-02 04:08 PM 编辑]
|
暂时没有评论
发表评论 - 不要忘了输入验证码哦! |