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 and there.
DashInsert
You have to implement a function with the following signature – dashInsert(num)
- The argument
num
is of type integer. - The function should return a string
Insert dashes '-'
between each two neighboring odd numbers in num
.
Don’t count zero as an odd number.
You can use any language you know.
Examples:
“9-9-946“
dashInsert(56730)
“567-30“
Here the task took me a little more time. I have used two loops – one to determine the number of dashes to be inserted and one to insert them. Furthermore, a function IsOdd was created, checking whether a digit is odd. Pretty much, it works flawlessly:
And 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
Option Explicit Option Compare Text Public Function DashInsert(lInput As Double) As String Dim strArray() As String Dim sResult() As String Dim sInput As String Dim lCount As Long Dim lResultCount As Long Dim lNumberOfDashes As Long Dim lLoop As Long sInput = Trim(Str(lInput)) lCount = Len(sInput) ReDim strArray(lCount - 1) lLoop = lCount For lLoop = 0 To lLoop - 1 If lLoop + 1 >= lCount Then Exit For strArray(lLoop) = Mid(sInput, lLoop + 1, 1) strArray(lLoop + 1) = Mid(sInput, lLoop + 2, 1) If IsOdd(strArray(lLoop)) And IsOdd(strArray(lLoop + 1)) Then lNumberOfDashes = lNumberOfDashes + 1 End If Next lLoop lResultCount = lCount - 1 + lNumberOfDashes ReDim sResult(lResultCount) lNumberOfDashes = 0 For lLoop = 0 To lLoop strArray(lLoop) = Mid(sInput, lLoop + 1, 1) If lLoop = lCount - 1 Then sResult(lLoop + lNumberOfDashes) = strArray(lLoop) Exit For End If strArray(lLoop + 1) = Mid(sInput, lLoop + 2, 1) sResult(lLoop + lNumberOfDashes) = strArray(lLoop) If IsOdd(strArray(lLoop)) And IsOdd(strArray(lLoop + 1)) Then lNumberOfDashes = lNumberOfDashes + 1 sResult(lLoop + lNumberOfDashes) = "-" End If Next lLoop DashInsert = Join(sResult, "") End Function Public Function IsOdd(lNumber As String) As Boolean IsOdd = CBool(CLng(lNumber) Mod 2) End Function |
Enjoy it!