VBScript: InStr with the AND operator

Consider the very simple VBScript code:
Dim sText
sText = "abc"
If InStr(sText,"a") And InStr(sText,"b") Then
WScript.Echo "Found both"
End If

At first glance you might think that this is fairly simple and will, as written, produce the output “Found both”.
Except it doesn’t.
However, modify the “If” line to the following:
If InStr(sText,"a") And InStr(sText,"c") Then
and it does output “Found both”.
So, you know that InStr finds text within a string, and clearly the variable sText contains “b” just as much as it contains “c”. So what’s going on?
It’s misbehaving because InStr returns the character number where the first instance of the string searched for begins. So:
returns 1
returns 2, and
returns 3.
Now think about how the “And” operator works with integers. It does binary maths on them.
Here’s the truth table for an AND gate:
0 0 | 0
0 1 | 0
1 0 | 0
1 1 | 1

and the binary to decimal conversion table:
d | b
0 | 00
1 | 01
2 | 10
3 | 11

So, the AND gate only gives a True (i.e. 1) output when both inputs are True (1).
So consider the original block of code, the first InStr in the If statement enumerates to position 1, the second emunerates to position 2. looking at the decimal to binary table above, performing an AND on the least significant bit (right-most column) of 1 AND 2 means 1 AND 0 which gives 0, and then on the most significant bit of 1 AND 2, i.e. 0 AND 1 which also gives 0. So the result is 00, in other words, False. Perform the same steps on 1 AND 3 however (which is a and c in the sText variable) and you end up with LSB = 1 AND 1 = 1, MSB = 0 AND 1 = 0. The “If” operator takes anything non-zero as “True” and so you end up with the “Found both” text being output.
So you need to be careful using logical operators with InStr – you may not get the results you’re expecting!
How to correct the code to make it function as intended? Change the If statement as follows:
If InStr(sText,"a")>0 And InStr(sText,"b")>0 Then
This way, the InStr result is then being combined with a greater than zero operation, with can only return True or False, so AND then works as expected. Searching for a AND b or a AND c both cause the “Found both” text to be displayed.

This entry was posted in Scripting, Windows and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s