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:

Beja

Expert
Licensed User
Longtime User
Thanks JakeBullet70,

A very small footprint code for a useful function.

Which libs involved?
 

emexes

Expert
Licensed User
Longtime 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
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…