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:
ExOH
Implement a function with the following signature: ExOh(str)
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 false
otherwise.
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.
Examples:
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
Option Explicit 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 End If Next lCount ExOH = (lHiks > 0) And (lHiks = lZero) End Function |
Enjoy it!