StrComp Function (Visual Basic)
Returns -1, 0, or 1, based on the result of a string comparison.
Public Shared Function StrComp( _
ByVal String1 As String, _
ByVal String2 As String, _
<Microsoft.VisualBasic.OptionCompareAttribute> _
Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _
) As Integer
Parameters
String1
Required. Any valid String expression.String2
Required. Any valid String expression.Compare
Optional. Specifies the type of string comparison. If Compare is omitted, the Option Compare setting determines the type of comparison.
Settings
The Compare argument settings are:
Constant |
Description |
---|---|
Binary |
Performs a binary comparison, based on a sort order derived from the internal binary representations of the characters. |
Text |
Performs a text comparison, based on a case-insensitive text sort order determined by your application's current culture information. |
Return Value
The StrComp function has the following return values.
If |
StrComp returns |
---|---|
String1 sorts ahead of String2 |
-1 |
String1 is equal to String2 |
0 |
String1 sorts after String2 |
1 |
Exceptions
Exception type |
Error number |
Condition |
---|---|---|
Compare value is not valid. |
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You can compare the error number against the Number Property (Err Object).) However, when possible, you should consider replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The strings are compared by alphanumeric sort values beginning with the first character. For further information on binary comparisons, textual comparisons, and sort order, see Option Compare Statement.
Security Note: |
---|
If your application makes security decisions based on the result of a comparison or case-change operation, then the operation should use the String.Compare method, and pass Ordinal or OrdinalIgnoreCase for the comparisonType argument. For more information, see How Culture Affects Strings in Visual Basic. |
Example
This example uses the StrComp function to return the results of a string comparison. If the third argument is omitted, the comparison type defined in the Option Compare statement or project defaults is performed.
' Defines variables.
Dim TestStr1 As String = "ABCD"
Dim TestStr2 As String = "abcd"
Dim TestComp As Integer
' The two strings sort equally. Returns 0.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Text)
' TestStr1 sorts after TestStr2. Returns -1.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Binary)
' TestStr2 sorts before TestStr1. Returns 1.
TestComp = StrComp(TestStr2, TestStr1)
Requirements
Namespace:Microsoft.VisualBasic
**Module:**Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)