Count occurance of a character in a string.

  • Thread starter Thread starter mario
  • Start date Start date
M

mario

Is there a built-in-function to count the number of
occurance of a character in a given string.

For example.

MyFunction('a','abba') would return 2.

Pls help

Thansk
Manik
 
No, but it would be easy to write one:

Function CountCharacter(SearchChar As String, Target As String) As Integer
Dim i As Integer
Dim Counter As Integer

For i = 1 To Len(Target)
If Mid(Target, i, 1) = SearchChar Then
Counter = Counter + 1
End If
Next i
CountCharacter = Counter

End Function
 
Is there a built-in-function to count the number of
occurance of a character in a given string.

No, but try this one:

Public Function CountChar(strA As String, strB As String) As Integer
Dim iPos As Integer
CountChar = 0
' check for validity
If Len(strA) = 0 Or Len(strA) > Len(strB) Then
MsgBox "Invalid arguments to CountChar", vbOKOnly
Exit Function
End If
For iPos = 1 to Len(strB)
If Mid(strB, iPos, Len(strA)) = strA Then
CountChar = CountChar + 1
End If
Next iPos
End Function
 
mario said:
Is there a built-in-function to count the number of
occurance of a character in a given string.

For example.

MyFunction('a','abba') would return 2.

No, there isn't. You have to create your own function.
Here's an air code example:

Public Function CountChar(lookfor As String, lookin As
String) As Long

Dim K As Long
For K = 1 To Len(lookin)
If Mid(lookin, K, 1) = lookfor Then
CountChar = CountChar + 1
End If
Next
End Function
 
Thank you very much sir.

mario
-----Original Message-----


No, but try this one:

Public Function CountChar(strA As String, strB As String) As Integer
Dim iPos As Integer
CountChar = 0
' check for validity
If Len(strA) = 0 Or Len(strA) > Len(strB) Then
MsgBox "Invalid arguments to CountChar", vbOKOnly
Exit Function
End If
For iPos = 1 to Len(strB)
If Mid(strB, iPos, Len(strA)) = strA Then
CountChar = CountChar + 1
End If
Next iPos
End Function


.
 
Back
Top