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?
phayzeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

JacamarCommented:
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
0
JacamarCommented:
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.
0
JacamarCommented:
Nevermind, the first one is right.............sorry about that
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

RMatzkaCommented:
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
0
deightonprogCommented:
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
0
kademingCommented:
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.
0
SSSoftwareCommented:
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
0
SSSoftwareCommented:
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
0
inthedarkCommented:
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
0
inthedarkCommented:
SSSoftware how about that! Exactly the same suggestion at exactly the same time!
0
sjpedroCommented:
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
0
AdsBCommented:
This is very similar to intedark's suggestion, but it runs much faster if your strings are very long.

Don;t worry about the difference if you know your strings will be less than, say, 500 characters in length.


use the same procedure as inthedark's last post, but use the following MsgBox line instead of his:-

MsgBox Len(sMyString) - Len(Replace(sMyString, "A", ""))

I tested this with a 6000 character string.  His took 20 seconds and mine took under 1 second.  I was amazed!

Hope this helps!


AdsB
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Da_WeaselSenior Software AnalystCommented:
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!
0
Da_WeaselSenior Software AnalystCommented:
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
0
Da_WeaselSenior Software AnalystCommented:
works with a single or multiple character strings
0
phayzeAuthor Commented:
Thanks. This one was the easiest to implement and use. :)
0
AdsBCommented:
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? ;-)
0
Da_WeaselSenior Software AnalystCommented:
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!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.