Count Words In A String

These two functions strip a string of html tags (if any) and count words. Make sure to set the Page tag to ValidateRequest="false"


Sub btnName_Click(s As Object, e As EventArgs)

Dim noTagStr As String = StripTags(txtstr.Text)

Dim count1 As Integer = CountWords(noTagStr)

lblCountwords.Text = count1

imgfoc.Focus()

End Sub


Public Function CountWords(ByVal value As String) As Integer

Dim collection As MatchCollection = Regex.Matches(value, "\S+")

Return collection.Count

End Function

    
Function StripTags(ByVal html As String) As String

Return Regex.Replace(html, "<.*?>|&.*?;", String.Empty)

End Function

HTML

<asp:TextBox ID="txtName" TextMode="MultiLine" Rows="5" Columns="30" runat="server" /> <asp:Button ID="btnName" runat="server" OnClick="btnName_Click" Text="Count Words" /><br /> NUMBER OF WORDS: <asp:Label ID="lblName" runat="server" /><br />

Test it! Enter some text and click "Count":




NUMBER OF WORDS: