Count Number of Words Using Regex in VB.NET
Create a Windows Form Application program in Visual Basic.Net that will allow users to count the number of words using VB.NET.
This tutorial will allow the user to use a label to count the number of words in a text box.
Before the tutorial the following are required to start:
- Microsoft Visual Studio 2008 – Above
The tutorial starts here:
- Open Microsoft Visual Studio 2012
- Select a New Project on the File menu.
- Select Visual Basic, Windows Form Application then click OK.
- We need to design our form by the following controls:
- 2 Label – 1 label for the counter’s label and 1 label for the counter itself.
- 1 Text box – text box for the Text.
- We will also name our form controls in this way:
- txttext is the name of the textbox for the Search text box.
- lblcount is the name of the button for the search button.
- This is how we design the form. (Feel free to layout your own)
Figure 1. Design of the Form
- Paste the following codes to add a function.
Function wordCount(ByVal str As String) Dim NumberOfWord As Integer NumberOfWord = UBound(Split(Trim(Replace(str, Space(2), Space(1))))) + 1 Return NumberOfWord End Function
These codes will recognize the word once it is separated by a space/split from a string.
- Double click the text box and paste the following code.
If txttext.Text = "" Then lblcount.Text = "Count Words: " & 0 Else lblcount.Text = "Count Words: " & wordCount(txttext.Text) End If
The code counts the number of words from the text box and displays it in the label named lblcount. If the text box doesn’t have any text it will return a “0” count.
We have created a sample program in VB.NET language using the Regex type that counts the number of words. Please follow the steps in order for you to run and execute the project properly.
The project and source code is available for download and you may modify it based on your preferences and requirements.
Name: Charlie Devera
Email Address: [email protected]
You may visit our facebook page for more information, inquiries and comments.
Hire our team to do the project.