Parse a String Into Words

Problem

You want to analyze a string and retrieve a list of all the words it contains.

Solution

Use the String.Split method. Depending on the complexity of the task, you might need to take additional steps to remove unwanted words.

Discussion

The String class includes a Split method that accepts an array of delimiter characters. The Split method divides the string every time one of these delimiters is found, and it returns the result as an array of strings. You can use this method with the space character to retrieve a list of words from a sentence.

Dim Sentence As String = "The quick brown fox jumps over the lazy dog." Dim Separators() As Char = {" "c} Dim Words() As String ' Split the sentence. Words = Sentence.Split(Separators) ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.