Counting the no of instances of a word

ritesh2190

Member
Joined
Jun 7, 2011
Messages
15
Programming Experience
1-3
i need to count the no of instances of a word in a string using vb.net
i can do the usual way as my problem is a little different

for eg i need to count the no of occurrences of -> in


tree_ptr->sub.another->valu=3;
 
Hi

You could try the following

VB.NET:
Dim testString As String = "->tree_ptr->sub.another->valu=3->"
        Dim test As Boolean = True
        Dim i As Integer = 0
        If testString.Contains("->") Then
            While test
                i = i + 1
                testString = testString.Substring(0, testString.LastIndexOf("->"))
                test = testString.Contains("->")
            End While
        End If

"i" will be the number of instances
 
Hi

You could try the following

VB.NET:
Dim testString As String = "->tree_ptr->sub.another->valu=3->"
        Dim test As Boolean = True
        Dim i As Integer = 0
        If testString.Contains("->") Then
            While test
                i = i + 1
                testString = testString.Substring(0, testString.LastIndexOf("->"))
                test = testString.Contains("->")
            End While
        End If

"i" will be the number of instances
It would be preferable to not do string modifications and not do duplicate searches for each match, since both can easily be avoided. You should look at String.IndexOf method, or Regex.Matches method (and get .Count).
 
Ah right you are. Did it using regx

VB.NET:
Dim pattern As String = "->"
Dim rgx As New Regex(pattern)
Dim sentence As String = "->tree_ptr->sub.an>other->valu=3->"
Dim cnt As Integer = rgx.Matches(sentence).Count
 
Back
Top