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 forHackBulgaria Programming 101v3. The tasks were given some months ago, so I assume it is OK to publish my solutions for them.
The previous task is resolved with VBA here.
So, this is the problem, as explained by the team of HackBulgaria:
AB Check
You have the implement a function, with the following signature: ABCheck(str)
.
The argument str
is of type string.
The function should return true
if the characters a
and b
are separated by exactly 3 places anywhere in the string at least once.
Otherwise return false
For example – "lane borrowed"
would result in true
because there is exactly three characters between a
and b
. .
You can use any language you know.
Examples:
ABCheck(“Laura sobs“) # true
What I did? I have decided to look at two cases – case one, is when we have first the “a” and four positions later the “b” and case two, is when we have first the “b”.
How I did it? With one for-loop and two checks for A and for B. Probably in Python the solution can be in less than 10 lines, but this one is in Excel 😛
Here is how it looks like:
Here comes the 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
Option Explicit Option Compare Text Public Function ABCheck(sInput As String) As Boolean Dim strArray() As String Dim sA As String Dim sB As String Dim lCount As Long lCount = Len(sInput) ReDim strArray(lCount - 1) If lCount < 5 Then Exit Function sA = "a" sB = "b" For lCount = 0 To lCount - 1 strArray(lCount) = Mid(sInput, lCount + 1, 1) If CStr(strArray(lCount)) = sA Then If lCount + 3 <= (Len(sInput) - 1) Then strArray(lCount + 4) = Mid(sInput, lCount + 5, 1) Debug.Print strArray(lCount + 4) Debug.Print Mid(sInput, lCount + 5, 1) If CStr(strArray(lCount + 4)) = sB Then ABCheck = True Exit Function End If End If ElseIf CStr(strArray(lCount)) = sB Then If lCount + 3 <= (Len(sInput) - 1) Then strArray(lCount + 4) = Mid(sInput, lCount + 5, 1) Debug.Print strArray(lCount + 4) Debug.Print Mid(sInput, lCount + 5, 1) If CStr(strArray(lCount + 4)) = sA Then ABCheck = True Exit Function End If End If End If Next lCount End Function |
Enjoy it! 🙂