devxlogo

Write concise code with the InStr function

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 wayIf UCase$(char) = "A" Or UCase$(char) = "E" Or UCase$(char) = "I" Or UCase$ _    (char) = "O"  Or UCase$(char) = "U" Then        ' it is a vowelEnd If' the more concise solutionIf InStr("AaEeIiOoUu", char) Then    ' it is a vowelEnd 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 wayIf LCase$(word) = "winter" Or LCase$(word) = "spring" Or LCase$(word) = _    "summer" Or LCase$(word) = "fall" Then        ' it is a season's nameEnd If' the more concise wayIf Instr(";winter;spring;summer;fall;", ";" & word & ";") Then    ' it is a season's nameEnd 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 waySelect 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 = 9End 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 semicolonsresult = InStr(";zero;;one;;;two;;;three;four;;five;;six;;;seven;eight;nine;", _    ";" & LCase$(word) & ";")  6

See also  How College Students Can Shape the Future of Tech Responsibility
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist