Sub CountOccurrences (text As String, match As String) As Int
Dim count As Int
Dim i As Int = -1
Do While i < text.Length
i = text.IndexOf2(match, i + 1)
If i = -1 Then
Exit
Else
count = count + 1
End If
Loop
Return count
End Sub
Sub CountOccurrences (text As String, match As String) As Int
Dim count As Int
Dim i As Int = -1
Do While i < text.Length
i = text.IndexOf2(match, i + 1)
If i = -1 Then
Exit
Else
count = count + 1
End If
Loop
Return count
End Sub
Sub CountOccurrences (text As String, match As String) As Int
Dim count As Int
Dim m As Matcher = Regex.Matcher($"\Q${match}\E"$, text)
Do While m.Find
count = count + 1
Loop
Return count
End Sub
If you are searching for a single character then the simplest way:
B4X:
Sub CountOccurrences (text As String, match As String) As Int
Dim count As Int
For i = 0 To text.Length - 1
If text.CharAt(i) = match Then count = count + 1
Next
Return count
End Sub
Can we carry this a little bit more by matching or not matching case:
B4X:
Log(CountOccurrences4("B4X community knows B4x and B4XPages ", "B4X", True))
B4X:
Sub CountOccurrences4(text As String, match As String, matchcsase As Boolean) As Int
If matchcsase Then
Return (text.Length - text.Replace(match, "").Length)/match.Length
End If
Return (text.Length - text.tolowercase.Replace(match.ToLowerCase, "").Length)/match.Length
End Sub