StrComp 函式 (Visual Basic)

更新:2007 年 11 月

依據字串比對結果,傳回 -1、0 或 1。

Public Shared Function StrComp( _
   ByVal String1 As String, _
   ByVal String2 As String, _
   <Microsoft.VisualBasic.OptionCompareAttribute> _
   Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _
) As Integer

參數

  • String1
    必要項。任何有效的 String 運算式。

  • String2
    必要項。任何有效的 String 運算式。

  • Compare
    選擇項。指定字串比較型別。如果省略 Compare,則 Option Compare 設定會決定比較型別。

設定

Compare 引數設定如下:

常數

描述

Binary

依據衍生自字元內部二進位表示的排序次序來執行二進位比對。

Text

依據應用程式目前文化特性資訊所決定的不區分大小寫文字排序次序來執行文字比對。

傳回值

StrComp 函式具有下列的傳回值。

如果

StrComp 傳回

String1 排序在右列項目前面:String2

-1

String1 等於String2

0

String1 排在右列項目之後:String2

1

例外狀況

例外狀況類型

錯誤代碼

條件

ArgumentException

5

Compare 值無效。

如果將使用非結構化錯誤處理的 Visual Basic 6.0 應用程式升級,請參閱「錯誤代碼」資料行 (您可以將錯誤代碼與 Number 屬性 (Err 物件) 比對)。但是,請盡可能考慮以 Visual Basic 的結構化例外處理概觀 取代這類錯誤控制項。

備註

字串比對依據按英數字元排序的值,從第一字元開始。如需二進位比較、文字比較和排序次序的詳細資訊,請參閱 Option Compare 陳述式

安全性注意事項:

如果應用程式會根據比較或大小寫變更作業的結果,做出安全性決策,則作業應該會使用 String.Compare 方法,並且傳遞 comparisonType 引數的 OrdinalOrdinalIgnoreCase。如需詳細資訊,請參閱在 Visual Basic 中文化特性如何影響字串

範例

這個範例會使用 StrComp 函式,傳回字串比對結果。如果省略第三引數,便會執行 Option Compare 陳述式或專案預設值中所定義的比較型別。

' 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)

需求

命名空間Microsoft.VisualBasic

模組:Strings

組件:Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)

請參閱

參考

字串操作摘要

InStr 函式 (Visual Basic)

ArgumentException

其他資源

Visual Basic 中的字串

Visual Basic 中的字串簡介