String manipulation can be a hassle using String Methods, but to speed up the process, you can use the Regex Class to quickly manipulate strings. The Regex class is commonly used to parse large amounts of text to replace, edit, or delete data in a string. Use the Matches Method to quickly count the words in a string. This method searches the string for all occurrences of a regular expression, such as words.
- Skill level:
Other People Are Reading
Launch Microsoft Visual Basic Express. Click "New Project" from the left pane of the window, and select "Windows Forms Application." Click "OK."
Double-click "TextBox" from the "Toolbox" pane to add a new checkbox control to the Form. Double-click "Button" to add a new button. Double-click "Button1" to open the Visual Basic Window.
Copy and paste the following in the first line to declare the Regex Class namespace:
Copy and paste the following code below "Button1_Click" to declare one variable and get the string typed in the text box by the user:
Dim word String As String
word String = Me.TextBox1.Text.ToString()
Copy and paste the following code to get the word count from the string variable:
Dim wrdCnt As MatchCollection = Regex.Matches(word String, "[\S]+")
Copy and paste the following code to display the word count using a message box:
Press "F5" to run your program and type a sentence into the text box. Press "Button1" to display the word count.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for