Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4,VB5,VB6,VBS
Expertise: beginner
Oct 16, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Write concise code with the InStr function

You can often use the Instr function in an unorthodox way to write more concise code. A typical example is when you need to test a single character:

' test whether CHAR contains a vowel
' the standard way
If UCase$(char) = "A" Or UCase$(char) = "E" Or UCase$(char) = "I" Or UCase$ _
    (char) = "O"  Or UCase$(char) = "U" Then
        ' it is a vowel
End If

' the more concise solution
If InStr("AaEeIiOoUu", char) Then
    ' it is a vowel
End If
You can also use InStr to check the contents of a variable against a list of multi-character words, using a delimiter character that can't appear in the word:

' test whether WORD contains the name of a season
' the standard way
If LCase$(word) = "winter" Or LCase$(word) = "spring" Or LCase$(word) = _
    "summer" Or LCase$(word) = "fall" Then
        ' it is a season's name
End If

' the more concise way
If Instr(";winter;spring;summer;fall;", ";" & word & ";") Then
    ' it is a season's name
End If
In some sames you can even use InStr to replace a Select Case block, but you must pay a lot of attention to the number of characters in the arguments:

' convert a string in the range from "zero" to "nine" to the corresponding 
' numeric value:

' the standard way
Select Case LCase$(word)
    Case "zero"
        result = 0
    Case "one"
        result = 1
    Case "two"
        result = 2
    Case "three"
        result = 3
    Case "four"
        result = 4
    Case "five"
        result = 5
    Case "six"
        result = 6
    Case "seven"
        result = 7
    Case "eight"
        result = 8
    Case "nine"
        result = 9
End Select

' the more concise way
' note that the longest word in the list is 5 characters long, so we must
' pad shorter strings with the necessary number of semicolons
result = InStr(";zero;;one;;;two;;;three;four;;five;;six;;;seven;eight;nine;", _
    ";" & LCase$(word) & ";") \ 6
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date