Count the occurrences of words in a String You can adopt multiple ways to find the occurrence of a word in a string. One of them is to use the String.IndexOf() which is one of the ways of finding the occurrence of the word. In VB.NET, use String.InStr().
Another simple way is to use Count property of the Regex.Matches() collection. However this method is slow. We will explore both these methods in the sample.
C#
string strOriginal = "These functions will come handy";
string strModified = String.Empty;
// Using IndexOf
int strt = 0;
int cnt = -1;
int idx = -1;
strOriginal = "She sells sea shells on the sea shore";
string srchString = "sea";
while (strt != -1)
{
strt = strOriginal.IndexOf(srchString, idx + 1);
cnt += 1;
idx = strt;
}
MessageBox.Show(srchString + " occurs " + cnt + " times");
// Using Regular Expression
System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(srchString);
int count = rex.Matches(strOriginal).Count;
MessageBox.Show(srchString + " occurs " + count + " times");VB.NET
Dim strOriginal As String = "These functions will come handy"
Dim strModified As String = String.Empty
' Using IndexOf
Dim strt As Integer = 0
Dim cnt As Integer = -1
Dim idx As Integer = -1
strOriginal = "She sells sea shells on the sea shore"
Dim srchString As String = "sea"
Do While strt <> -1
strt = strOriginal.IndexOf(srchString, idx + 1)
cnt += 1
idx = strt
Loop
MessageBox.Show(srchString & " occurs " & cnt & " times")
' Using Regular Expression
Dim rex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(srchString)
Dim count As Integer = rex.Matches(strOriginal).Count
MessageBox.Show(srchString & " occurs " & count & " times")