Android Question Find how many occurrences of a character in a string

Scotter

Active Member
Licensed User
I'm trying to find how many CRLFs exist within a string. This is done MANY times, within a loop.
I'm calling the following function in order to get it done each time.
Is there a faster way?
Thanks!
B4X:
Sub CountChars(value As String, ch As Char) As Int
  Dim cnt As Int = 0
  Dim c As Char
  For i = 0 To value.Length-1
      c=value.CharAt(i)
    If (c = ch) Then cnt = cnt+ 1
  Next
  Return cnt
End Sub
 

Ed Brown

Active Member
Licensed User
Longtime User
Hi @Scotter

Try
B4X:
Dim sTest1 As String = $"hello${CRLF}world${CRLF}"$
Log(sTest1)
Dim sTest2 As String = sTest1.Replace(CRLF, "")
Log(sTest2)
Log($"count: ${sTest1.Length - sTest2.Length}"$)

The idea here is to use the built-in Replace method to change the string you are looking for with an empty string. Then take the lengths of both and subtract the new string length from the original string length.

For your code sample try
B4X:
Sub CountChars(value as String, substr as String) as Int
  Dim t as String = value.Replace(substr, "")
  Return value.Length - t.Length
End Sub
 
Upvote 0

Scotter

Active Member
Licensed User
Hi @Scotter

Try
B4X:
Dim sTest1 As String = $"hello${CRLF}world${CRLF}"$
Log(sTest1)
Dim sTest2 As String = sTest1.Replace(CRLF, "")
Log(sTest2)
Log($"count: ${sTest1.Length - sTest2.Length}"$)

The idea here is to use the built-in Replace method to change the string you are looking for with an empty string. Then take the lengths of both and subtract the new string length from the original string length.

For your code sample try
B4X:
Sub CountChars(value as String, substr as String) as Int
  Dim t as String = value.Replace(substr, "")
  Return value.Length - t.Length
End Sub
Thank you!
 
Upvote 0
Top