jsp
jsp

Reputation: 2636

Using instr when string is nothing

I have the following condition

If InStr("a,b,c", stringA) > 0 OrElse (InStr("y,z", stringB) > 0 AndAlso value = 0) Then endif

COndition 1 is false so i check for condition 2 that is "(InStr("y,z", stringB) > 0 AndAlso value = 0) "

What puzzles me is that when stringB is nothing it still falls into the if condition and executes the code.

On first look it would seem that when stringB is nothing condition2 would fail and as a result would not fall into the if condition.

Any explanation why this would happen?

thanks

Upvotes: 0

Views: 463

Answers (1)

ckittel
ckittel

Reputation: 6646

The InStr() function has an optional overload that starts with the position to start checking (the "start position".) If that is excluded (like as in your example), then it starts searching that the beginning of the string, as you would expect.

When Nothing is passed into the function for stringB, the "start position" is returned. So, one would think that "0" is returned, but in reality you are probably getting "1" back. That is because the InStr function treats the string as a 1-based array of characters instead of a 0-based array of characters. So the "start position" that is returned is 1, not 0; and as we all know 1 is > 0 :) (Source on MSDN)

Upvotes: 2

Related Questions