The InStr() Method in VB .NET

String Position

The InStr( ) method of string variables tells you what the position of one string is inside another. For example, if your string was "" and you wanted to know if the string contained the @ symbol, you could use InStr( ) Method. You would use it like this

FirstString = ""
SecondString = "@"

position = InStr( FirstString, SecondString )

The variable FirstString is the string we want to search; SecondString is what we want to search for. You can specify a starting position for the search to begin. If you do, this number goes at the start (the default is zero):

position = InStr( 1, FirstString, SecondString )

The variable called position has to be an integer variable. That's because the InStr() Method returns a number, and not text. In the code above, position would have a value of 3. That's because the @ symbols starts at the third letter of "".

(Note: the InStr() Method starts counting at 1, and not zero like Chars(), which is very confusing!)

If the string you're searching for is not found, then the value placed inside of your integer variable (position in our case) is zero. That enables you to code something like this:

If position = 0 Then

MessageBox.Show("Not a Valid email address: There was No @ Sign")

End If


Another useful string method is Substring. We'll see how to use it in the next part.