Android Code Snippet Count sub strings

Subname: StringCount

Description: I just came across this while searching for something else, I thought it was worth sharing. Count the number of sub strings in a string. This will also give a character count for a single character TargetStr.

B4X:
Sub StringCount(StringToSearch As String,TargetStr As String,IgnoreCase As Boolean) As Int
    If IgnoreCase Then
        StringToSearch = StringToSearch.ToLowerCase
        TargetStr = TargetStr.ToLowerCase
    End If

    Return (StringToSearch.Length - StringToSearch.Replace(TargetStr,"").Length) / TargetStr.Length

End Sub

Usage:
B4X:
Dim Test1 As String = "Test to Count the characters in this test string"

    Log(StringCount(Test1,"test",True))

Tags: Count characters strings b4a b4j b4i
 
Last edited:

sorex

Expert
Licensed User
Longtime User
Steve,

the result will be 2 for that example?
 

stevel05

Expert
Licensed User
Longtime User
Hi Sorex, yes because ignore case is selected.
 

Ed Brown

Active Member
Licensed User
Longtime User
Nice work @stevel05
Might also be worth adding a quick check to ensure that the TargetStr is not empty which would result in a divide-by-zero error.
 

stevel05

Expert
Licensed User
Longtime User
Thanks Ed, not my work, just passing on knowledge from some lateral thinkers. I thought of that and tried it, but it does not give an error, just returns 0 matches on B4j at least. if it does on the other platforms, you could use Max(TargetStr.Length,1) as a divisor instead of checking for an empty string.
 
Top