Solved

# Counting Number of 'A's in a String

Posted on 2003-02-27
Medium Priority
446 Views
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?
0
Question by:phayze
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 4
• 3
• 2
• +7

LVL 2

Expert Comment

ID: 8037215
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

LVL 2

Expert Comment

ID: 8037220
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

LVL 2

Expert Comment

ID: 8037227
Nevermind, the first one is right.............sorry about that
0

Expert Comment

ID: 8037464
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

LVL 18

Expert Comment

ID: 8037506

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

LVL 1

Expert Comment

ID: 8037646
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

LVL 4

Expert Comment

ID: 8037745
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

LVL 4

Expert Comment

ID: 8037746
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

LVL 17

Expert Comment

ID: 8037748

Hope this helps:~)

Private Sub Command2_Click()
Dim sMyString As String
sMyString = "ABCDEHA"
MsgBox CStr(UBound(Split(sMyString, "A")))
End Sub
0

LVL 17

Expert Comment

ID: 8037758
SSSoftware how about that! Exactly the same suggestion at exactly the same time!
0

LVL 1

Expert Comment

ID: 8037829
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

Dim strMyString As String

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)

End Sub
0

LVL 4

Accepted Solution

ID: 8037846
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!

0

LVL 3

Expert Comment

ID: 8038320
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

LVL 3

Expert Comment

ID: 8038335
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

LVL 3

Expert Comment

ID: 8038340
works with a single or multiple character strings
0

Author Comment

ID: 8038505
Thanks. This one was the easiest to implement and use. :)
0

LVL 4

Expert Comment

ID: 8038530
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

LVL 3

Expert Comment

ID: 8039273
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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asseâ€¦
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). Uâ€¦
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process fromâ€¦
###### Suggested Courses
Course of the Month11 days, 22 hours left to enroll