VBA – Check distance between two chars in a string

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.

download

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:

<class=””>ABCheck(after badly) # false
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:

abcCheck

Here comes the code:

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! 🙂