Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Write concise code with the InStr function

Total Hit ( 2044)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


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:

Click here to copy the following block
' 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:

Click here to copy the following block
' 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:

Click here to copy the following block
' 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


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.