In the current article, I will present the way to calculate the number of chars in a string with VBA. The inspiration came from the entry exam for HackBulgaria Programming 101v3. The tasks were given some months ago, so I assume it is OK to publish my solutions for them 🙂
As far as the guys teach Python, I can bet that no one tought of resolving the tasks with VBA. Anyway, here is the problem:
Implement a function with the following signature:
str is of type string.
The function should return
true if there is an equal number of x’s and o’s in
str. It should return
Things to know:
- Only these two letters will be entered in the string, no punctuation or numbers.
- You don’t have to check for valid input.
- You can use any language you know.
ExOh(‘oooxoo‘) # false
So, what I did? Actually nothing complicated – an Array and a for-loop did the work for me pretty fast. If I had an option to use for-each for the string, it would have been actually even better. But this is VBA, so lets hate it less 🙂
This is how it looks like:
Here comes the outstanding code :
Option Compare Text
Public Function ExOH(sInput As String) As Boolean
Dim strArray() As String
Dim sZero As String
Dim sHiks As String
Dim lHiks As Long
Dim lZero As Long
Dim lCount As Long
lCount = Len(sInput)
ReDim strArray(lCount - 1)
sZero = "o"
sHiks = "x"
For lCount = 0 To lCount - 1
strArray(lCount) = Mid(sInput, lCount + 1, 1)
If CStr(strArray(lCount)) = sZero Then
lZero = lZero + 1
ElseIf CStr(strArray(lCount)) = sHiks Then
lHiks = lHiks + 1
ExOH = (lHiks > 0) And (lHiks = lZero)