Public Class Form1
Private Function WordPercentage(ByVal AllWords As Boolean, Optional ByVal WordToFind As String = Nothing) As String
'If you specify False to matching AllWords and don't provide a WordToFind then there can be no results
If Not (AllWords) AndAlso WordToFind = Nothing Then Return Nothing
'Create a lookup table that can store every word found in the RichTextBox and the number of times it occurs
Dim UniqueWords As New Dictionary(Of String, Integer)
'If you only want the percentage for a specific word then set the word in the Table. (No further entries will be added)
If Not (AllWords) Then UniqueWords.Add(WordToFind, 0)
'Split the TichTextBox using the Space char. This will leave you with a string array containing all the words
Dim RTBWords() As String = RichTextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
'Calculate the total number of words in the RichTextBox (needed to calculate the percentage)
Dim NoWords As Integer = RTBWords.Count
'If there are no words then exit the sub
If NoWords = 0 Then Return Nothing
For Each Word As String In RTBWords
'+++++++ Remove this line if you do not want to allow case-insensitive matches +++++++
Word = Word.ToLower
'Check if the current word was found in the UniqueWords lookup table
If UniqueWords.ContainsKey(Word) Then
'If it was then add 1 to the word count
UniqueWords.Item(Word) += 1
Else
'If you want to find the percentage of all the words in the RichTextBox then add each word into the Lookup table
If AllWords Then UniqueWords.Add(Word, 1)
End If
Next Word
'++++++++++++ Edit the Output to suit your own needs ++++++++++++
'Compile the results using stringbuilder
Dim Output As New System.Text.StringBuilder("The following Words were found in the RichTextBox:" & vbCrLf & vbCrLf)
'For every word that was found in the RichTextBox
For Each Entry As KeyValuePair(Of String, Integer) In UniqueWords
'Append the word to the output and the calculated percentage
Output.AppendLine(Entry.Key & ": " & ((Entry.Value * 100) / NoWords).ToString & "%")
Next Entry
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'Return the Output
Return Output.ToString
End Function
End Class