Android Code Snippet CountChar() Count the number of times a char appears in a string.

SubName: CountChar
Description: Counts the number of times a char appears in a string.
Dependencies/Libraries: None


B4X:
' Counts the number of times a char appears in a string.
' Param - searchMe, the string to be searched
' Param - findMe, the single char to search for
Public Sub CountChar(searchMe As String, findMe As Char) As Int

    If Not(searchMe.Contains(findMe)) Then Return 0

    Dim CountMe As Int = 0

    For x = 0 To searchMe.Length - 1
        If searchMe.CharAt(x) = findMe Then
            CountMe = CountMe + 1
        End If
    Next

    Return CountMe

End Sub


Tags: character count, string
 
Last edited:

emexes

Expert
Licensed User
Standing on the OP's shoulders, here's one that works for strings too (and probably slightly quicker, for those counting CPU cycles):

B4X:
' Counts the number of times a string or char appears in a string.
' Param - SearchMe, the string to be searched
' Param - FindMe, the string or char to search for
public Sub CountString(SearchMe As String, FindMe As String) As Int
   
    Dim NumFound As Int = 0
   
    Dim P As Int = SearchMe.IndexOf(FindMe)
    Do Until P < 0    'IndexOf functions return -1 if not found
        NumFound = NumFound + 1
        P = SearchMe.IndexOf2(FindMe, P + 1)    'continue search at next char after previous occurrence
    Loop
   
    Return NumFound
   
End Sub
 
Top