Android Code Snippet Count sub strings

Discussion in 'Code Snippets' started by stevel05, Sep 8, 2015.

  1. stevel05

    stevel05 Expert Licensed User

    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.

    Code:
    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:
    Code:
    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: Dec 19, 2015
  2. Erel

    Erel Administrator Staff Member Licensed User

    Nice. Note that it will work with B4i as well.
     
    stevel05 likes this.
  3. sorex

    sorex Expert Licensed User

    Steve,

    the result will be 2 for that example?
     
  4. stevel05

    stevel05 Expert Licensed User

    Hi Sorex, yes because ignore case is selected.
     
  5. Ed Brown

    Ed Brown Active Member Licensed 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.
     
  6. stevel05

    stevel05 Expert Licensed 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.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice