Link to home
Start Free TrialLog in
Avatar of phayze
phayze

asked on

Counting Number of 'A's in a String

Does anyone know how to count the total number that a certain character shows up in a string? I want my function to count how many 'A's are in my string... Any help?
Avatar of Jacamar
Jacamar

Try this

dim MyString1 as string
dim MyString2 as string

MyString1 = "whatever you want it to be."

Do until MyString2 = "."
inI = inI + 1
MyString2 = Mid(MyString1, 1, inI)
If MyString2 = "A" or MyString2 = "a" then
inNumAs = inNumAs + 1
Loop


inNumAs is the number of A's in the string
dim MyString1 as string
dim MyString2 as string

MyString1 = "whatever you want it to be."

Do until MyString2 = "."
inI = inI + 1
MyString2 = Mid(MyString1, inI)
If MyString2 = "A" or MyString2 = "a" then
inNumAs = inNumAs + 1
Loop


Sorry this is a correction.
Nevermind, the first one is right.............sorry about that
Yes, but you can have it faster.

Public Function CountAs(s as String) as Long
  Dim Parts() as String
  Parts=Split(s,"a",,vbTextCompare)
  CountAs=UBound(Parts)
End Function
Private Sub Form_Load()

    MsgBox CountA("Aardvark")

End Sub

Private Function CountA(sX As String) As Long

    Dim c As Long
   
    c = 1
   
    While InStr(c, UCase(sX), "A")
        CountA = CountA + 1
        c = InStr(c, UCase(sX), "A") + 1
    Wend
       
End Function
Here's a function into which you can pass a string and the character you're counting.  It will return the number of characters found:

<------Begin Code------>

Function CountChar (MyString as string, SearchChar as string)


     Dim i, CharCount, ShiftAmt, CurChar
     CharCount = 0
     
     If SearchChar >= "a" Then
          ShiftAmt = -32
     Else
          ShiftAmt = 32
     End If
     
     For i = 1 To Len(MyString)
          CurChar = Mid(MyString, i, 1)
          'MsgBox CurChar = Chr(Asc(SearchChar)+ShiftAmt)
          If CurChar = SearchChar Or CurChar = Chr(Asc(SearchChar)+ShiftAmt) Then
               CharCount = CharCount + 1
          End If
     Next
     
     CountChar = CharCount
     
End Function
<------End Code------>

So, if you wanted to store the result in a variable called NumChar the function call would look like the following:

NumChar = CountChar("A fancy schmancy string", "a")

This is a case insensitive function.

Hope it helps.
To phayze,

The simplest way is to use the SPLIT VB Function.

Private Function FindChar(S as string, LookFor as string) as Integer
Dim Ary() as string
Ary = Split(S,LookFor)

On error goto NoChars

FindChar = ubound(ary) +1)
Exit Function

FindChar = 0

End Function
To phayze,

The simplest way is to use the SPLIT VB Function.

Private Function FindChar(S as string, LookFor as string) as Integer
Dim Ary() as string
Ary = Split(S,LookFor)

On error goto NoChars

FindChar = ubound(ary) +1)
Exit Function

FindChar = 0

End Function
Avatar of inthedark
How about this real fast way:

Hope this helps:~)

Private Sub Command2_Click()
Dim sMyString As String
sMyString = "ABCDEHA"
MsgBox CStr(UBound(Split(sMyString, "A")))
End Sub
SSSoftware how about that! Exactly the same suggestion at exactly the same time!
Here is variation of kademing solution

You can pass any string and will give you the total numbers of 'A' and 'a'.  You can choose upper case or lower case to count.  and you can also add more characters to it.
Hope it helps

Private Sub Form_Load()
Dim strMyString As String

strMyString = "AdAhdjdajdfjfjAa"
        Dim intI As Integer
        Dim counter As Integer
        For intI = 1 To Len(strMyString)
        If Mid(strMyString, intI, 1) Like "[aA]" Then
            counter = counter + 1
        End If
        Next intI
        MsgBox (counter)
Unload Me

End Sub
ASKER CERTIFIED SOLUTION
Avatar of AdsB
AdsB

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
building off of AdsB's Replace method here is a nice reusable function for doing this:

Function CharCount(ByVal s As String, ByVal c As String, ByVal CaseSensitive As Boolean) As Integer
    If CaseSensitive Then
        CharCount = (Len(s) - Len(Replace(s, c, ""))) / Len(c)
    Else
        CharCount = (Len(s) - Len(Replace(s, UCase(c), "", , , vbTextCompare))) / Len(c)
    End If
End Function


Here is a how you would use it:
USAGE: CharCount(stringToSearch,stringToFind,[True or False])

Dim strAs As String
strAs = "aaaAAjssasAsassaasaAakkA"
MsgBox CharCount(strAs, "a", False) 'returns 14
MsgBox CharCount(strAs, "A", False) 'returns 14
MsgBox CharCount(strAs, "a", True) 'returns 9
MsgBox CharCount(strAs, "A", True) 'returns 5
MsgBox CharCount(strAs, "sa", True) 'returns 4
MsgBox CharCount(strAs, "as", False) 'returns 4

I may have gone a little over board here, but since everyone was 'one-upping' each other I figured I would put an end to it....hehe
Hope you like it!
oops  here is a repost of that function:
Function CharCount(ByVal s As String, ByVal c As String, Optional ByVal CaseSensitive As Boolean = True) As Integer
    If CaseSensitive Then
        CharCount = (Len(s) - Len(Replace(s, c, ""))) / Len(c)
    Else
        CharCount = (Len(s) - Len(Replace(s, UCase(c), "", , , vbTextCompare))) / Len(c)
    End If
End Function
the last parameter tells the function whether or not the Count is Case Sensitive (true = Case Sensitive, false = Not Case Sensitive)  defaults to true
works with a single or multiple character strings
Avatar of phayze

ASKER

Thanks. This one was the easiest to implement and use. :)
Da_Weasel,

There are different kinds of "one-upping".

I tried to go "one-up" on the answers that went before me.

But you seem to have gone "one-up" on the question!  phayze didn't ask for a reusable routine, case-sensitivity or even the ability to specify what character is looked for.  He just asked for a count of "A"s.

I think my answer does what he asked for - no more and no less.  It is a one-line answer which precisely answers the question.  Can anyone better it?

Alternatively, we could go on forever adding bells & whistles.  I could add stuff to Da_Weasel's function.  Maybe a StartPosition parameter and some error handling?  Perhaps, something that makes your breakfast at the same time? ;-)
I wasn't shooting for a "Good Answer!"  email here, just jumping on the bandwagon.  It seemed that everyone's post built off of each others and the geek in me came out.  I never thought to use the Replace function for counting, and your idea got the gears in my head going.  This has now become a very flexible and somewhat more complex function and added to my string module library, and probably soon a class.

Thanks for the great solution!