Export (0) Print
Expand All

InStr Function

Returns an integer specifying the start position of the first occurrence of one string within another.

Public Shared Function InStr(_
   Optional ByVal Start As Integer, _
   ByVal String1 As String, _
   ByVal String2 As String, _
) As Integer

-or-

Public Shared Function InStr(_
   Optional ByVal Start As Integer, _
   ByVal String1 As String, _
   ByVal String2 As String, _
   Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _
) As Integer

Parameters

Start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. The start index is 1 based.
String1
Required. String expression being searched.
String2
Required. String expression sought.
Compare
Optional. Specifies the type of string comparison. If Compare is omitted, the Option Compare setting determines the type of comparison. Specify a valid LCID (LocaleID) to use locale-specific rules in the comparison.

Settings

The compare argument settings are:

Constant Value Description
Binary 0 Performs a binary comparison
Text 1 Performs a text comparison

Return Values

If InStr returns
String1 is zero length or Nothing 0
String2 is zero length or Nothing start
String2 is not found 0
String2 is found within String1 Position where match begins
Start > String2 0

Exceptions/Errors

Exception type Error number Condition
ArgumentException 5 Start < 1.
Note   The InStrB function in previous versions of Visual Basic returns a number of bytes rather than a character position. It is used primarily for converting strings in double-byte character set (DBCS) applications. All Visual Basic .NET strings are in Unicode, and InStrB is no longer supported.

Example

This example uses the InStr function to return the position of the first occurrence of one string within another.

Dim SearchString, SearchChar As String
Dim MyPos As Integer

SearchString ="XXpXXpXXPXXP"   ' String to search in.
SearchChar = "P"   ' Search for "P".

' A textual comparison starting at position 4. Returns 6.
MyPos = InStr(4, SearchString, SearchChar, CompareMethod.Text)   

' A binary comparison starting at position 1. Returns 9.
MyPos = InStr(1, SearchString, SearchChar, CompareMethod.Binary)

' Comparison is binary by default (last argument is omitted).
MyPos = InStr(SearchString, SearchChar)   ' Returns 9.

MyPos = InStr(1, SearchString, "W")   ' Returns 0.

Requirements

Namespace: Microsoft.VisualBasic

Module: Strings

Assembly: Microsoft Visual Basic .NET Runtime (in Microsoft.VisualBasic.dll)

See Also

Strings | String Manipulation | InStrRev Function | Option Compare Statement | StrComp Function | ArgumentException Class | Programming Element Support Changes Summary

Show:
© 2014 Microsoft