String.Compare 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
比較兩個指定的 String 物件,並回傳一個整數,表示它們在排序順序中的相對位置。
多載
備註
所有方法的 Compare 超載都會回傳一個 32 位元的有符號整數,表示兩個比較元件之間的詞法關係。
| 價值觀 | 狀況 |
|---|---|
| 低於零 | 第一個子字串在排序順序中位於第二個子字串之前。 |
| 零 | 子字串在排序順序中出現的位置相同,或 length 為零。 |
| 大於零 | 第一個子字串依排序順序緊接第二個子字串。 |
警告
如果可能,你應該呼叫包含Compare參數的方法的超載StringComparison。 如需詳細資訊,請參閱使用字串的最佳做法。
Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)
利用指定的比較選項與文化特定資訊比較兩個指定 String 物件的子串來影響比較,並回傳一個整數,表示兩個子串在排序順序中的關係。
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, System::Globalization::CultureInfo ^ culture, System::Globalization::CompareOptions options);
public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);
static member Compare : string * int * string * int * int * System.Globalization.CultureInfo * System.Globalization.CompareOptions -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, culture As CultureInfo, options As CompareOptions) As Integer
參數
- strA
- String
比較中第一個用的字串。
- indexA
- Int32
子串在 strA中的起始位置。
- strB
- String
這是第二個用來比較的弦。
- indexB
- Int32
子串在 strB中的起始位置。
- length
- Int32
子串中可比較的最大字元數。
- culture
- CultureInfo
提供文化特定比較資訊的物件。 如果 culture 為 null,則會使用目前的文化特性。
- options
- CompareOptions
進行比較時可使用的選項(例如忽略大小寫或符號)。
傳回
一個整數表示兩個子串之間的詞彙關係,如下表所示。
| 價值 | 條件 |
|---|---|
| 低於零 | 子 strA 串在排序順序中排在子 strB 字串之前。
|
| 零 | 子字串在排序順序中出現的位置相同,或 length 為零。
|
| 大於零 | 子 strA 字串在子字串之後,依排序順序跟隨子 strB 字串。
|
例外狀況
options 不是一個 CompareOptions 數值。
indexA 大於 strA.Length。
-或-
indexB 大於 strB.Length。
-或-
indexA, , indexB或 length 為負值。
-或-
或 strAstrB 或 是 null,且 length 大於零。
範例
以下範例使用比較 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 兩人姓氏的方法。 接著會依字母順序列出這些資料。
string name1 = "Jack Smith";
string name2 = "John Doe";
// Get position of character after the space character.
int index1 = name1.IndexOf(" ");
index1 = index1 < 0 ? 0 : ++index1;
int index2 = name2.IndexOf(" ");
index2 = index2 < 0 ? 0 : ++index2;
int length = Math.Max(name1.Length, name2.Length);
Console.WriteLine("Sorted alphabetically by last name:");
if (String.Compare(name1, index1, name2, index2, length,
new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0)
Console.WriteLine("{0}\n{1}", name1, name2);
else
Console.WriteLine("{0}\n{1}", name2, name1);
// The example displays the following output:
// Sorted alphabetically by last name:
// John Doe
// Jack Smith
open System
open System.Globalization
let name1 = "Jack Smith"
let name2 = "John Doe"
// Get position of character after the space character.
let index1 =
let i = name1.IndexOf " "
if i < 0 then 0 else i + 1
let index2 =
let i = name2.IndexOf " "
if i < 0 then 0 else i + 1
let length = max name1.Length name2.Length
printfn "Sorted alphabetically by last name:"
if String.Compare(name1, index1, name2, index2, length, CultureInfo "en-US", CompareOptions.IgnoreCase) < 0 then
printfn $"{name1}\n{name2}"
else
printfn $"{name2}\n{name1}"
// The example displays the following output:
// Sorted alphabetically by last name:
// John Doe
// Jack Smith
Imports System.Globalization
Module Example
Public Sub Main()
Dim name1 As String = "Jack Smith"
Dim name2 = "John Doe"
' Get position of space character.
Dim index1 As Integer = name1.IndexOf(" ")
index1 = CInt(IIf(index1 < 0, 0, index1 - 1))
Dim index2 As Integer = name2.IndexOf(" ")
index1 = CInt(IIf(index1 < 0, 0, index1 - 1))
Dim length As Integer = Math.Max(name1.Length, name2.Length)
Console.WriteLIne("Sorted alphabetically by last name:")
If String.Compare(name1, index1, name2, index2, length, _
New CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0 Then
Console.WriteLine("{0}{1}{2}", name1, vbCrLf, name2)
Else
Console.WriteLine("{0}{1}{2}", name2, vbCrLf, name1)
End If
End Sub
End Module
' The example displays the following output;
' Sorted alphabetically by last name:
' John Doe
' Jack Smith
備註
比較的子串從位置 strAindexAstrBindexB開始,位置為 。 第一子串的長度即為負strA值的長度indexA。 第二子串的長度即為負strBindexB值的長度。
要比較的字元數為兩個子串長度較短者, length且 。 這些 indexA、 indexB、 和 length 參數必須為非負。
比較利用該 culture 參數取得文化特定的資訊,例如字模規則及個別字元的字母順序。 例如,某個文化可以指定某些字元組合被視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序取決於前後的字元。
注意事項
此 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 方法主要設計用於排序或字母排序操作。 當方法呼叫的主要目的是判斷兩個子字串是否等價(也就是說,方法呼叫的目的是測試回傳值為零時),則不應使用此方法。 要判斷兩個字串是否等價,請呼叫 該 Equals 方法。
其中一個或兩個 可以strAstrB是 null。 根據定義,任何字串(包括 String.Empty)都比大於空參考,而兩個空參考則比較相等。
比較還可以由 options 參數來指定,該參數包含列舉中的一個或多個成員 System.Globalization.CompareOptions 。 然而,由於此方法的目的是進行培養敏感的弦比較,與CompareOptions.OrdinalCompareOptions.OrdinalIgnoreCase值對此不影響。
當發現不等式或兩個子串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於其中一串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
給呼叫者的注意事項
字元集包含可忽略的字元。
Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)該方法在進行語言或文化敏感比較時,並未考慮這些字元。 要辨識比較中可忽略的字元,請為參數提供 Ordinal 或 OrdinalIgnoreCaseoptions 值。
另請參閱
適用於
Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
比較兩個指定 String 物件的子串,忽略或尊重其情況,並利用文化特定資訊影響比較,並回傳一個整數,表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo? culture);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture);
static member Compare : string * int * string * int * int * bool * System.Globalization.CultureInfo -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean, culture As CultureInfo) As Integer
參數
- strA
- String
比較中第一個用的字串。
- indexA
- Int32
子字串在 strA中的位置。
- strB
- String
這是第二個用來比較的弦。
- indexB
- Int32
子字串在 strB中的位置。
- length
- Int32
子串中可比較的最大字元數。
- ignoreCase
- Boolean
true在比較時忽略格;否則,。 false
- culture
- CultureInfo
提供文化特定比較資訊的物件。 如果 culture 為 null,則會使用目前的文化特性。
傳回
一個整數表示兩個比較物之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 | 子 strA 串在排序順序中排在子 strB 字串之前。
|
| 零 | 子字串在排序順序中出現的位置相同,或 length 為零。
|
| 大於零 | 子 strA 字串在子字串之後,依排序順序跟隨子 strB 字串。
|
例外狀況
indexA大於strA......Length
-或-
indexB大於strB......Length
-或-
indexA, , indexB或 length 為負值。
-或-
或 strAstrB 或 是 null,且 length 大於零。
範例
以下範例比較兩個使用不同文化的子字串,並忽略子字串的情況。 文化的選擇會影響字母「I」的比較方式。
// Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using System;
using System.Globalization;
class Sample5
{
public static void Main()
{
// 0123456
String str1 = "MACHINE";
String str2 = "machine";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
Console.WriteLine("Ignore case, Turkish culture:");
result = String.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR"));
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
Console.WriteLine();
Console.WriteLine("Ignore case, invariant culture:");
result = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
}
}
/*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.
Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*/
// Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
open System
open System.Globalization
// 0123456
let str1 = "MACHINE"
let str2 = "machine"
printfn $"\nstr1 = '{str1}', str2 = '{str2}'"
printfn "Ignore case, Turkish culture:"
let result = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo "tr-TR")
let str = if result < 0 then "less than" elif result > 0 then "greater than" else "equal to"
printf $"Substring '{str1.Substring(4, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(4, 2)}' in '{str2}'."
printfn "\nIgnore case, invariant culture:"
let result2 = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture)
let str3 = if result < 0 then "less than" elif result > 0 then "greater than" else "equal to"
printf $"Substring '{str1.Substring(4, 2)}' in '{str1}' is "
printf $"{str3} "
printfn $"substring '{str2.Substring(4, 2)}' in '{str2}'."
(*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.
Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
Imports System.Globalization
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "MACHINE"
Dim str2 As [String] = "machine"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
Console.WriteLine("Ignore case, Turkish culture:")
result = [String].Compare(str1, 4, str2, 4, 2, True, New CultureInfo("tr-TR"))
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2)
Console.WriteLine()
Console.WriteLine("Ignore case, invariant culture:")
result = [String].Compare(str1, 4, str2, 4, 2, True, CultureInfo.InvariantCulture)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'MACHINE', str2 = 'machine'
'Ignore case, Turkish culture:
'Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.
'
'Ignore case, invariant culture:
'Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
'
備註
比較的子串從 開始strAindexA於 ,在 strBindexB。 和 indexA 都是indexB零基底;也就是說,和 strA 中的strB第一個字元位於位置零,而非位置一。 第一子串的長度等於負strA一的長度indexA。 第二子串的長度等於負strBindexB一的長度。
要比較的字元數為兩個子串長度較短者, length且 。 這些 indexA、 indexB、 和 length 參數必須為非負。
比較利用該 culture 參數取得文化特定的資訊,如字模規則及個別字元的字母順序。 例如,文化可以指定某些字元組合視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序順序取決於前後的字元。
比較是使用單字排序規則進行的。 關於字、字串和序數排序的更多資訊,請參見 System.Globalization.CompareOptions。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩個子串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
用序數比較將路徑名稱與「檔案」進行比較。 正確的程式碼如下:
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。
Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)該方法在進行語言或文化敏感比較時,並未考慮這些字元。 要辨識比較中可忽略的字元,呼叫該 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 方法並為參數提供 Ordinal 或 OrdinalIgnoreCaseoptions 值。
另請參閱
適用於
Compare(String, Int32, String, Int32, Int32, StringComparison)
利用指定規則比較兩個指定 String 物件的子字串,並回傳一個整數,表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, StringComparison comparisonType);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, StringComparison comparisonType);
static member Compare : string * int * string * int * int * StringComparison -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, comparisonType As StringComparison) As Integer
參數
- strA
- String
比較中第一個用的字串。
- indexA
- Int32
子字串在 strA中的位置。
- strB
- String
這是第二個用來比較的弦。
- indexB
- Int32
子字串在 strB中的位置。
- length
- Int32
子串中可比較的最大字元數。
- comparisonType
- StringComparison
其中一個列舉值,用來指定比較時要使用的規則。
傳回
一個32位元帶符號的整數,表示兩個比較元之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 | 子 strA 串在排序順序中排在子 strB 字串之前。
|
| 零 | 子串在排序順序中出現在同一位置,或參數 length 為零。
|
| 大於零 | 子 strA 字串在子字串之後,依排序順序跟隨子 strB 字串。
|
例外狀況
indexA大於strA......Length
-或-
indexB大於strB......Length
-或-
indexA, , indexB或 length 為負值。
-或-
或 indexAindexB 或 是 null,且 length 大於零。
comparisonType 不是一個 StringComparison 數值。
範例
以下範例比較兩個子字串。
String str1 = "machine";
String str2 = "device";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);
/*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
open System
let str1 = "machine"
let str2 = "device"
printfn "\nstr1 = '{str1}', str2 = '{str2}'"
let result = String.Compare(str1, 2, str2, 0, 2)
let str =
if result < 0 then "less than"
elif result > 0 then "greater than"
else "equal to"
printf $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(0, 2)}' in '{str2}'."
(*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "machine"
Dim str2 As [String] = "device"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
result = [String].Compare(str1, 2, str2, 0, 2)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'
備註
比較的子串從 中strAindexA開始,strBindexB在 中 。 和 indexA 都是indexB零基底;也就是說,和 strA 中的strB第一個字元位於位置零,而非位置一。 第一子串的長度等於負strA一的長度indexA。 第二子串的長度等於負strBindexB一的長度。
要比較的字元數為兩個子串長度較短者, length且 。 這些 indexA、 indexB、 和 length 參數必須為非負。
參數 comparisonType 指示比較是否應使用當前或不變的文化,採用或忽略比較的案例,或使用詞彙(文化敏感)或序數(文化敏感)排序規則。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩個子串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
用序數比較將路徑名稱與「檔案」進行比較。 正確的程式碼如下:
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。
Compare(String, Int32, String, Int32, Int32, StringComparison)該方法在進行語言或文化敏感比較時,並未考慮這些字元。 要辨識比較中可忽略的字元,請為參數提供 Ordinal 或 OrdinalIgnoreCasecomparisonType 值。
另請參閱
適用於
Compare(String, Int32, String, Int32, Int32, Boolean)
比較兩個指定 String 物件的子串,忽略或尊重它們的格,並回傳一個整數表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase);
public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
static member Compare : string * int * string * int * int * bool -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean) As Integer
參數
- strA
- String
比較中第一個用的字串。
- indexA
- Int32
子字串在 strA中的位置。
- strB
- String
這是第二個用來比較的弦。
- indexB
- Int32
子字串在 strB中的位置。
- length
- Int32
子串中可比較的最大字元數。
- ignoreCase
- Boolean
true在比較時忽略格;否則,。 false
傳回
一個32位元帶符號的整數,表示兩個比較元之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 | 子 strA 串在排序順序中排在子 strB 字串之前。
|
| 零 | 子字串在排序順序中出現的位置相同,或 length 為零。
|
| 大於零 | 子 strA 字串在子字串之後,依排序順序跟隨子 strB 字串。
|
例外狀況
indexA大於strA......Length
-或-
indexB大於strB......Length
-或-
indexA, , indexB或 length 為負值。
-或-
或 indexAindexB 或 是 null,且 length 大於零。
範例
以下範例對兩個子串進行兩次比較,僅在情況下有所不同。 第一個比較忽略了案例,第二個比較則考慮案例。
String str1 = "MACHINE";
String str2 = "machine";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
Console.WriteLine("Ignore case:");
result = String.Compare(str1, 2, str2, 2, 2, true);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
Console.WriteLine();
Console.WriteLine("Honor case:");
result = String.Compare(str1, 2, str2, 2, 2, false);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
/*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.
Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*/
open System
let str1 = "MACHINE"
let str2 = "machine"
printfn $"\nstr1 = '{str1}', str2 = '{str2}'"
printfn "Ignore case:"
let result = String.Compare(str1, 2, str2, 2, 2, true)
let str =
if result < 0 then "less than"
elif result > 0 then "greater than"
else "equal to"
printf $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(2, 2)}' in '{str2}'.\n"
printfn "Honor case:"
let result2 = String.Compare(str1, 2, str2, 2, 2, false)
let str3 =
if result < 0 then "less than"
elif result > 0 then "greater than"
else "equal to"
printfn $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str3} "
printfn $"substring '{str2.Substring(2, 2)}' in '{str2}'."
(*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.
Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean)
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "MACHINE"
Dim str2 As [String] = "machine"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
Console.WriteLine("Ignore case:")
result = [String].Compare(str1, 2, str2, 2, 2, True)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2)
Console.WriteLine()
Console.WriteLine("Honor case:")
result = [String].Compare(str1, 2, str2, 2, 2, False)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'MACHINE', str2 = 'machine'
'Ignore case:
'Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.
'
'Honor case:
'Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
'
備註
比較的子串從 開始strAindexA於 ,在 strBindexB。 和 indexA 都是indexB零基底;也就是說,和 strA 中的strB第一個字元位於位置零。 第一子串的長度等於負strA一的長度indexA。 第二子串的長度等於負strBindexB一的長度。
要比較的字元數為兩個子串長度較短者, length且 。 這些 indexA、 indexB、 和 length 參數必須為非負。
比較利用當前文化獲取特定文化資訊,如字模規則及個別字元的字母順序。 例如,文化可以指定某些字元組合視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序順序取決於前後的字元。
比較是使用單字排序規則進行的。 關於字、字串和序數排序的更多資訊,請參見 System.Globalization.CompareOptions。
警告
在比較字串時,你應該呼叫該 Compare(String, Int32, String, Int32, Int32, StringComparison) 方法,這需要你明確指定該方法所使用的字串比較類型。 如需詳細資訊,請參閱使用字串的最佳做法。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩個子串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
路徑名稱需要以不變方式比較。 正確的程式碼如下。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。
Compare(String, Int32, String, Int32, Int32, Boolean)該方法在進行語言或文化敏感比較時,並未考慮這些字元。 要辨識比較中可忽略的字元,呼叫該 Compare(String, Int32, String, Int32, Int32, StringComparison) 方法並為參數提供 Ordinal 或 OrdinalIgnoreCasecomparisonType 值。
另請參閱
適用於
Compare(String, Int32, String, Int32, Int32)
比較兩個指定 String 物件的子串,並回傳一個整數,表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length);
public static int Compare(string strA, int indexA, string strB, int indexB, int length);
public static int Compare(string? strA, int indexA, string? strB, int indexB, int length);
static member Compare : string * int * string * int * int -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer) As Integer
參數
- strA
- String
比較中第一個用的字串。
- indexA
- Int32
子字串在 strA中的位置。
- strB
- String
這是第二個用來比較的弦。
- indexB
- Int32
子字串在 strB中的位置。
- length
- Int32
子串中可比較的最大字元數。
傳回
一個 32 位元的有號整數,表示兩個比較元件之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 | 子 strA 串在排序順序中排在子 strB 字串之前。
|
| 零 | 子字串在排序順序中出現的位置相同,或 length 為零。
|
| 大於零 | 子 strA 字串在子字串之後,依排序順序跟隨子 strB 字串。
|
例外狀況
indexA大於strA......Length
-或-
indexB大於strB......Length
-或-
indexA, , indexB或 length 為負值。
-或-
或 indexAindexB 或 是 null,且 length 大於零。
範例
以下範例比較兩個子字串。
String str1 = "machine";
String str2 = "device";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);
/*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
open System
let str1 = "machine"
let str2 = "device"
printfn "\nstr1 = '{str1}', str2 = '{str2}'"
let result = String.Compare(str1, 2, str2, 0, 2)
let str =
if result < 0 then "less than"
elif result > 0 then "greater than"
else "equal to"
printf $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(0, 2)}' in '{str2}'."
(*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "machine"
Dim str2 As [String] = "device"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
result = [String].Compare(str1, 2, str2, 0, 2)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'
備註
比較的子串從 中strAindexA開始,strBindexB在 中 。 和 indexA 都是indexB零基底;也就是說,和 strA 中的strB第一個字元位於位置零。 第一子串的長度等於負strA一的長度indexA。 第二子串的長度等於負strBindexB一的長度。
要比較的字元數為兩個子串長度較短者, length且 。 這些 indexA、 indexB、 和 length 參數必須為非負。
比較利用當前文化獲取特定文化資訊,如字模規則及個別字元的字母順序。 例如,文化可以指定某些字元組合視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序順序取決於前後的字元。
比較是使用單字排序規則進行的。 關於字、字串和序數排序的更多資訊,請參見 System.Globalization.CompareOptions。
警告
在比較字串時,你應該呼叫該 Compare(String, Int32, String, Int32, Int32, StringComparison) 方法,這需要你明確指定該方法所使用的字串比較類型。 如需詳細資訊,請參閱使用字串的最佳做法。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩個子串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
用序數比較將路徑名稱與「檔案」進行比較。 正確的程式碼如下:
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。
Compare(String, Int32, String, Int32, Int32)該方法在進行語言或文化敏感比較時,並未考慮這些字元。 要辨識比較中可忽略的字元,呼叫該 Compare(String, Int32, String, Int32, Int32, StringComparison) 方法並為參數提供 Ordinal 或 OrdinalIgnoreCasecomparisonType 值。
另請參閱
適用於
Compare(String, String, CultureInfo, CompareOptions)
利用指定的比較選項與文化特定資訊比較兩個指定 String 物件,影響比較結果,並回傳一個整數,顯示兩字串在排序順序中的關係。
public:
static int Compare(System::String ^ strA, System::String ^ strB, System::Globalization::CultureInfo ^ culture, System::Globalization::CompareOptions options);
public static int Compare(string? strA, string? strB, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
public static int Compare(string strA, string strB, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);
static member Compare : string * string * System.Globalization.CultureInfo * System.Globalization.CompareOptions -> int
Public Shared Function Compare (strA As String, strB As String, culture As CultureInfo, options As CompareOptions) As Integer
參數
- strA
- String
要比較的第一個字串。
- strB
- String
要比較的第二個字串。
- culture
- CultureInfo
提供特定文化比較資訊的文化。 如果 culture 為 null,則會使用目前的文化特性。
- options
- CompareOptions
進行比較時可使用的選項(例如忽略大小寫或符號)。
傳回
一個32位元有符號整數,表示與 strA之間的strB詞彙關係,如下表所示
| 價值 | 條件 |
|---|---|
| 低於零 |
strA依排序順序排列。strB
|
| 零 |
strA與排序順序相同。strB
|
| 大於零 |
strA 依排序順序跟隨 strB 。
|
例外狀況
options 不是一個 CompareOptions 數值。
範例
以下範例以三種不同方式比較兩個字串:使用語言比較來描述 en-US 文化;en-US 文化使用語言格敏感比較;並使用序數比較。 它說明了三種比較方法如何產生三種不同的結果。
using System;
using System.Globalization;
public class Example0
{
public static void Main()
{
string string1 = "brother";
string string2 = "Brother";
string relation;
int result;
// Cultural (linguistic) comparison.
result = String.Compare(string1, string2, new CultureInfo("en-US"),
CompareOptions.None);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console.WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// Cultural (linguistic) case-insensitive comparison.
result = String.Compare(string1, string2, new CultureInfo("en-US"),
CompareOptions.IgnoreCase);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console.WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// Culture-insensitive ordinal comparison.
result = String.CompareOrdinal(string1, string2);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console.WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// The example produces the following output:
// 'brother' comes before 'Brother'.
// 'brother' is the same as 'Brother'.
// 'brother' comes after 'Brother'.
}
}
open System
open System.Globalization
let string1 = "brother"
let string2 = "Brother"
// Cultural (linguistic) comparison.
let result = String.Compare(string1, string2, CultureInfo "en-US", CompareOptions.None)
let relation =
if result > 0 then "comes after"
elif result = 0 then "is the same as"
else "comes before"
printfn $"'{string1}' {relation} '{string2}'."
// Cultural (linguistic) case-insensitive comparison.
let result2 = String.Compare(string1, string2, CultureInfo "en-US", CompareOptions.IgnoreCase)
let relation2 =
if result2 > 0 then "comes after"
elif result2 = 0 then "is the same as"
else "comes before"
printfn $"'{string1}' {relation2} '{string2}'."
// Culture-insensitive ordinal comparison.
let result3 = String.CompareOrdinal(string1, string2)
let relation3 =
if result2 > 0 then "comes after"
elif result2 = 0 then "is the same as"
else "comes before"
printfn $"'{string1}' {relation} '{string2}'."
// The example produces the following output:
// 'brother' comes before 'Brother'.
// 'brother' is the same as 'Brother'.
// 'brother' comes after 'Brother'.
Imports System.Globalization
Public Module Example
Public Sub Main()
Dim string1 As String = "brother"
Dim string2 As String = "Brother"
Dim relation As String
Dim result As Integer
' Cultural (linguistic) comparison.
result = String.Compare(string1, string2, _
New CultureInfo("en-US"), CompareOptions.None)
If result > 0 Then
relation = "comes after"
ElseIf result = 0 Then
relation = "is the same as"
Else
relation = "comes before"
End If
Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)
' Cultural (linguistic) case-insensitive comparison.
result = String.Compare(string1, string2, _
New CultureInfo("en-US"), CompareOptions.IgnoreCase)
If result > 0 Then
relation = "comes after"
ElseIf result = 0 Then
relation = "is the same as"
Else
relation = "comes before"
End If
Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)
' Culture-insensitive ordinal comparison.
result = String.CompareOrdinal(string1, string2)
If result > 0 Then
relation = "comes after"
ElseIf result = 0 Then
relation = "is the same as"
Else
relation = "comes before"
End If
Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)
End Sub
End Module
' The example produces the following output:
' 'brother' comes before 'Brother'.
' 'brother' is the same as 'Brother'.
' 'brother' comes after 'Brother'.
備註
比較利用該 culture 參數取得文化特定的資訊,例如字模規則及個別字元的字母順序。 例如,某個文化可以指定某些字元組合被視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序取決於前後的字元。
注意事項
此 Compare(String, String, CultureInfo, CompareOptions) 方法主要設計用於排序或字母排序操作。 當方法呼叫的主要目的是判斷兩個字串是否等價(也就是為了測試回傳值為零)時,不應使用此方法。 要判斷兩個字串是否等價,請呼叫 該 Equals 方法。
比較還可以由 options 參數來指定,該參數包含列舉中的一個或多個成員 CompareOptions 。 然而,由於此方法的目的是進行培養敏感的弦比較,與CompareOptions.OrdinalCompareOptions.OrdinalIgnoreCase值對此不影響。
其中一種或兩種比較都可以是 null。 根據定義,任何字串(包括 String.Empty)都比大於空參考,而兩個空參考則比較相等。
當發現不等式或兩串字串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於其中一串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。
給呼叫者的注意事項
字元集包含可忽略的字元,這些字元是執行語言或區分文化特性的比較時不會考慮的字元。
Compare(String, String, CultureInfo, CompareOptions)該方法在進行文化敏感比較時,並未考慮這些特徵。 要辨識比較中可忽略的字元,請為參數提供 Ordinal 或 OrdinalIgnoreCaseoptions 值。
另請參閱
適用於
Compare(String, String, Boolean, CultureInfo)
比較兩個指定 String 物件,忽略或尊重其情況,並利用文化特定資訊影響比較,並回傳一個整數表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, System::String ^ strB, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static int Compare(string? strA, string? strB, bool ignoreCase, System.Globalization.CultureInfo? culture);
public static int Compare(string strA, string strB, bool ignoreCase, System.Globalization.CultureInfo culture);
static member Compare : string * string * bool * System.Globalization.CultureInfo -> int
Public Shared Function Compare (strA As String, strB As String, ignoreCase As Boolean, culture As CultureInfo) As Integer
參數
- strA
- String
要比較的第一個字串。
- strB
- String
要比較的第二個字串。
- ignoreCase
- Boolean
true在比較時忽略格;否則,。 false
- culture
- CultureInfo
提供文化特定比較資訊的物件。 如果 culture 為 null,則會使用目前的文化特性。
傳回
一個32位元帶符號的整數,表示兩個比較元之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 |
strA依排序順序排列。strB
|
| 零 |
strA與排序順序相同。strB
|
| 大於零 |
strA 依排序順序跟隨 strB 。
|
範例
以下範例說明文化如何影響比較。 在捷克-捷克共和國文化中,「ch」是指大於「d」的單一字元。 然而,在英語與美國文化中,「ch」由兩個字元組成,而「c」小於「d」。
public static void Main()
{
String str1 = "change";
String str2 = "dollar";
String relation;
relation = symbol(String.Compare(str1, str2, false, new CultureInfo("en-US")));
Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2);
relation = symbol(String.Compare(str1, str2, false, new CultureInfo("cs-CZ")));
Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2);
}
private static String symbol(int r)
{
String s = "=";
if (r < 0) s = "<";
else if (r > 0) s = ">";
return s;
}
/*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*/
let symbol r =
if r < 0 then "<"
elif r > 0 then ">"
else "="
let str1 = "change"
let str2 = "dollar"
let relation1 =
String.Compare(str1, str2, false, CultureInfo "en-US")
|> symbol
printfn $"For en-US: {str1} {relation1} {str2}"
let relation2 =
String.Compare(str1, str2, false, CultureInfo "cs-CZ")
|> symbol
printfn $"For cs-CZ: {str1} {relation2} {str2}"
(*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*)
Imports System.Globalization
_
Class Sample
Public Shared Sub Main()
Dim str1 As [String] = "change"
Dim str2 As [String] = "dollar"
Dim relation As [String] = Nothing
relation = symbol([String].Compare(str1, str2, False, New CultureInfo("en-US")))
Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2)
relation = symbol([String].Compare(str1, str2, False, New CultureInfo("cs-CZ")))
Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2)
End Sub
Private Shared Function symbol(r As Integer) As [String]
Dim s As [String] = "="
If r < 0 Then
s = "<"
Else
If r > 0 Then
s = ">"
End If
End If
Return s
End Function 'symbol
End Class
'
'This example produces the following results.
'For en-US: change < dollar
'For cs-CZ: change > dollar
'
備註
比較利用該 culture 參數取得文化特定的資訊,如字模規則及個別字元的字母順序。 例如,文化可以指定某些字元組合視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序順序取決於前後的字元。
比較是使用單字排序規則進行的。 關於字、字串和序數排序的更多資訊,請參見 System.Globalization.CompareOptions。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩串字串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
用序數比較將路徑名稱與「檔案」進行比較。 正確的程式碼如下:
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。 Compare(String, String, Boolean, CultureInfo)該方法在進行文化敏感比較時,並未考慮這些特徵。 例如,若以下程式碼在 .NET Framework 4 或更新版本上執行,若使用不變文化將「animal」與「Ani-mal」(使用軟連字號或 U+00AD)進行大小寫不區分的比較,表示這兩個字串是等價的。
string s1 = "Ani\u00ADmal";
string s2 = "animal";
Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
s1, s2, String.Compare(s1, s2, true,
CultureInfo.InvariantCulture));
// The example displays the following output:
// Comparison of 'Ani-mal' and 'animal': 0
open System
open System.Globalization
let s1 = "Ani\u00ADmal"
let s2 = "animal"
printfn $"Comparison of '{s1}' and '{s2}': {String.Compare(s1, s2, true, CultureInfo.InvariantCulture)}"
// The example displays the following output:
// Comparison of 'Ani-mal' and 'animal': 0
Imports System.Globalization
Module Example
Public Sub Main()
Dim s1 As String = "Ani" + ChrW(&h00AD) + "mal"
Dim s2 As String = "animal"
Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
s1, s2, String.Compare(s1, s2, True,
CultureInfo.InvariantCulture))
End Sub
End Module
' The example displays the following output:
' Comparison of 'ani-mal' and 'animal': 0
要辨識字串比較中可忽略的字元,呼叫該 Compare(String, String, CultureInfo, CompareOptions) 方法並為參數提供 或 OrdinalOrdinalIgnoreCaseoptions 的值。
另請參閱
- Int32
- CompareOrdinal(String, String)
- CompareTo(Object)
- IsPrefix(String, String, CompareOptions)
- Boolean
適用於
Compare(String, String, StringComparison)
使用指定規則比較兩個指定 String 物件,並回傳一個整數,表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, System::String ^ strB, StringComparison comparisonType);
public static int Compare(string strA, string strB, StringComparison comparisonType);
public static int Compare(string? strA, string? strB, StringComparison comparisonType);
static member Compare : string * string * StringComparison -> int
Public Shared Function Compare (strA As String, strB As String, comparisonType As StringComparison) As Integer
參數
- strA
- String
要比較的第一個字串。
- strB
- String
要比較的第二個字串。
- comparisonType
- StringComparison
其中一個列舉值,用來指定比較時要使用的規則。
傳回
一個32位元帶符號的整數,表示兩個比較元之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 |
strA依排序順序排列。strB
|
| 零 |
strA與排序順序相同。strB
|
| 大於零 |
strA 依排序順序跟隨 strB 。
|
例外狀況
comparisonType 不是一個 StringComparison 數值。
範例
以下範例比較了三個字母「I」的版本。 結果會受到培養物選擇、是否忽略個案,以及是否進行序數比較所影響。
// This example demonstrates the
// System.String.Compare(String, String, StringComparison) method.
using System;
using System.Threading;
class Sample
{
public static void Main()
{
string intro = "Compare three versions of the letter I using different " +
"values of StringComparison.";
// Define an array of strings where each element contains a version of the
// letter I. (An array of strings is used so you can easily modify this
// code example to test additional or different combinations of strings.)
string[] threeIs = new string[3];
// LATIN SMALL LETTER I (U+0069)
threeIs[0] = "\u0069";
// LATIN SMALL LETTER DOTLESS I (U+0131)
threeIs[1] = "\u0131";
// LATIN CAPITAL LETTER I (U+0049)
threeIs[2] = "\u0049";
string[] unicodeNames =
{
"LATIN SMALL LETTER I (U+0069)",
"LATIN SMALL LETTER DOTLESS I (U+0131)",
"LATIN CAPITAL LETTER I (U+0049)"
};
StringComparison[] scValues =
{
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase
};
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
Console.WriteLine(
"The current culture is {0}.\n", Thread.CurrentThread.CurrentCulture.Name);
// Determine the relative sort order of three versions of the letter I.
foreach (StringComparison sc in scValues)
{
Console.WriteLine("StringComparison.{0}:", sc);
// LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
Test(0, 1, sc, threeIs, unicodeNames);
// LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
Test(0, 2, sc, threeIs, unicodeNames);
// LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
Test(1, 2, sc, threeIs, unicodeNames);
Console.WriteLine();
}
}
protected static void Test(
int x, int y, StringComparison comparison, string[] testI, string[] testNames)
{
string resultFmt = "{0} is {1} {2}";
string result = "equal to";
int cmpValue = 0;
cmpValue = String.Compare(testI[x], testI[y], comparison);
if (cmpValue < 0)
result = "less than";
else if (cmpValue > 0)
result = "greater than";
Console.WriteLine(resultFmt, testNames[x], result, testNames[y]);
}
}
/*
This code example produces the following results:
Compare three versions of the letter I using different values of StringComparison.
The current culture is en-US.
StringComparison.CurrentCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.CurrentCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.InvariantCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.OrdinalIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
*/
// This example demonstrates the
// System.String.Compare(String, String, StringComparison) method.
open System
open System.Threading
let test x y (comparison: StringComparison) (testI: string[]) (testNames: string[]) =
let cmpValue = String.Compare(testI[x], testI[y], comparison)
let result =
if cmpValue < 0 then
"less than"
elif cmpValue > 0 then
"greater than"
else
"equal to"
printfn $"{testNames[x]} is {result} {testNames[y]}"
let intro = "Compare three versions of the letter I using different values of StringComparison."
// Define an array of strings where each element contains a version of the
// letter I. (An array of strings is used so you can easily modify this
// code example to test additional or different combinations of strings.)
let threeIs =
[|// LATIN SMALL LETTER I (U+0069)
"\u0069"
// LATIN SMALL LETTER DOTLESS I (U+0131)
"\u0131"
// LATIN CAPITAL LETTER I (U+0049)
"\u0049" |]
let unicodeNames =
[| "LATIN SMALL LETTER I (U+0069)"
"LATIN SMALL LETTER DOTLESS I (U+0131)"
"LATIN CAPITAL LETTER I (U+0049)" |]
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
Console.Clear()
printfn $"{intro}"
// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
printfn $"The current culture is {Thread.CurrentThread.CurrentCulture.Name}.\n"
// Determine the relative sort order of three versions of the letter I.
for sc in scValues do
printfn $"StringComparison.{sc}:"
// LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
test 0 1 sc threeIs unicodeNames
// LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
test 0 2 sc threeIs unicodeNames
// LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
test 1 2 sc threeIs unicodeNames
printfn ""
(*
This code example produces the following results:
Compare three versions of the letter I using different values of StringComparison.
The current culture is en-US.
StringComparison.CurrentCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.CurrentCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.InvariantCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.OrdinalIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
*)
' This example demonstrates the
' System.String.Compare(String, String, StringComparison) method.
Imports System.Threading
Class Sample
Public Shared Sub Main()
Dim intro As String = "Compare three versions of the letter I using different " & _
"values of StringComparison."
' Define an array of strings where each element contains a version of the
' letter I. (An array of strings is used so you can easily modify this
' code example to test additional or different combinations of strings.)
Dim threeIs(2) As String
' LATIN SMALL LETTER I (U+0069)
threeIs(0) = "i"
' LATIN SMALL LETTER DOTLESS I (U+0131)
threeIs(1) = "ı"
' LATIN CAPITAL LETTER I (U+0049)
threeIs(2) = "I"
Dim unicodeNames As String() = { _
"LATIN SMALL LETTER I (U+0069)", _
"LATIN SMALL LETTER DOTLESS I (U+0131)", _
"LATIN CAPITAL LETTER I (U+0049)" }
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
'
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because the culture-specific comparisons
' can produce different results with different cultures.
Console.WriteLine("The current culture is {0}." & vbCrLf, _
Thread.CurrentThread.CurrentCulture.Name)
' Determine the relative sort order of three versions of the letter I.
Dim sc As StringComparison
For Each sc In scValues
Console.WriteLine("StringComparison.{0}:", sc)
' LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
Test(0, 1, sc, threeIs, unicodeNames)
' LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
Test(0, 2, sc, threeIs, unicodeNames)
' LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
Test(1, 2, sc, threeIs, unicodeNames)
Console.WriteLine()
Next sc
End Sub
Protected Shared Sub Test(ByVal x As Integer, ByVal y As Integer, _
ByVal comparison As StringComparison, _
ByVal testI() As String, ByVal testNames() As String)
Dim resultFmt As String = "{0} is {1} {2}"
Dim result As String = "equal to"
Dim cmpValue As Integer = 0
'
cmpValue = String.Compare(testI(x), testI(y), comparison)
If cmpValue < 0 Then
result = "less than"
ElseIf cmpValue > 0 Then
result = "greater than"
End If
Console.WriteLine(resultFmt, testNames(x), result, testNames(y))
End Sub
End Class
'
'This code example produces the following results:
'
'Compare three versions of the letter I using different values of StringComparison.
'The current culture is en-US.
'
'StringComparison.CurrentCulture:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.CurrentCultureIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.InvariantCulture:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.InvariantCultureIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.Ordinal:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.OrdinalIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
備註
參數 comparisonType 指示比較是否應使用當前或不變的文化,採用或忽略比較的案例,或使用詞彙(文化敏感)或序數(文化敏感)排序規則。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩串字串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
用序數比較將路徑名稱與「檔案」進行比較。 正確的程式碼如下:
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。
Compare(String, String, StringComparison)該方法在進行文化敏感比較時,並未考慮這些特徵。 要辨識比較中可忽略的字元,請為參數提供 Ordinal 或 OrdinalIgnoreCasecomparisonType 值。
另請參閱
適用於
Compare(String, String, Boolean)
比較兩個指定 String 物件,忽略或尊重其大小,並回傳一個整數,表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, System::String ^ strB, bool ignoreCase);
public static int Compare(string strA, string strB, bool ignoreCase);
public static int Compare(string? strA, string? strB, bool ignoreCase);
static member Compare : string * string * bool -> int
Public Shared Function Compare (strA As String, strB As String, ignoreCase As Boolean) As Integer
參數
- strA
- String
要比較的第一個字串。
- strB
- String
要比較的第二個字串。
- ignoreCase
- Boolean
true在比較時忽略格;否則,。 false
傳回
一個32位元帶符號的整數,表示兩個比較元之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 |
strA依排序順序排列。strB
|
| 零 |
strA與排序順序相同。strB
|
| 大於零 |
strA 依排序順序跟隨 strB 。
|
範例
以下範例說明該 Compare(String, String, Boolean) 方法等同於使用 ToUpper 或 ToLower 在比較字串時。
// Create upper-case characters from their Unicode code units.
String stringUpper = "\x0041\x0042\x0043";
// Create lower-case characters from their Unicode code units.
String stringLower = "\x0061\x0062\x0063";
// Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower);
// Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0
? "true" : "false");
// The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
String.Compare(stringUpper, stringLower, true) == 0
? "true" : "false" );
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
open System
// Create upper-case characters from their Unicode code units.
let stringUpper = "\x0041\x0042\x0043"
// Create lower-case characters from their Unicode code units.
let stringLower = "\x0061\x0062\x0063"
// Display the strings.
printfn $"Comparing '{stringUpper}' and '{stringLower}':"
// Compare the uppercased strings the result is true.
printfn $"The Strings are equal when capitalized? %b{String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0}"
// The previous method call is equivalent to this Compare method, which ignores case.
printfn $"The Strings are equal when case is ignored? %b{String.Compare(stringUpper, stringLower, true) = 0}"
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
Public Module Example
Public Sub Main()
' Create upper-case characters from their Unicode code units.
Dim stringUpper As String = ChrW(&H41) + ChrW(&H42) + ChrW(&H43)
' Create lower-case characters from their Unicode code units.
Dim stringLower As String = ChrW(&H61) + ChrW(&H62) + ChrW(&H63)
' Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower)
' Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
If(String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0,
"true", "false"))
' The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
If(String.Compare(stringUpper, stringLower, true) = 0,
"true", "false"))
End Sub
End Module
' The example displays the following output:
' Comparing 'ABC' and 'abc':
' The Strings are equal when capitalized? true
' The Strings are equal when case is ignored? true
備註
比較利用當前文化獲取特定文化資訊,如字模規則及個別字元的字母順序。 例如,文化可以指定某些字元組合視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序順序取決於前後的字元。
比較是使用單字排序規則進行的。 關於字、字串和序數排序的更多資訊,請參見 System.Globalization.CompareOptions。
警告
在比較字串時,你應該呼叫該 Compare(String, String, StringComparison) 方法,這需要你明確指定該方法所使用的字串比較類型。 如需詳細資訊,請參閱使用字串的最佳做法。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩串字串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
用序數比較將路徑名稱與「檔案」進行比較。 正確的程式碼如下:
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。 Compare(String, String, Boolean)該方法在進行文化敏感比較時,並未考慮這些特徵。 例如,將「animal」與「Ani-mal」進行文化敏感且不區分大小寫的比較(使用軟連字號或 U+00AD),表示這兩個字串是等價的。
string s1 = "Ani\u00ADmal";
string s2 = "animal";
Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
s1, s2, String.Compare(s1, s2, true));
// The example displays the following output:
// Comparison of 'Ani-mal' and 'animal': 0
open System
let s1 = "Ani\u00ADmal"
let s2 = "animal"
printfn $"Comparison of '{s1}' and '{s2}': {String.Compare(s1, s2, true)}"
// The example displays the following output:
// Comparison of 'Ani-mal' and 'animal': 0
Module Example
Public Sub Main()
Dim s1 As String = "Ani" + ChrW(&h00AD) + "mal"
Dim s2 As String = "animal"
Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
s1, s2, String.Compare(s1, s2, True))
End Sub
End Module
' The example displays the following output:
' Comparison of 'ani-mal' and 'animal': 0
要辨識字串比較中可忽略的字元,呼叫該 Compare(String, String, StringComparison) 方法並為參數提供 或 OrdinalOrdinalIgnoreCasecomparisonType 的值。
另請參閱
適用於
Compare(String, String)
比較兩個指定的 String 物件,並回傳一個整數,表示它們在排序順序中的相對位置。
public:
static int Compare(System::String ^ strA, System::String ^ strB);
public static int Compare(string strA, string strB);
public static int Compare(string? strA, string? strB);
static member Compare : string * string -> int
Public Shared Function Compare (strA As String, strB As String) As Integer
參數
- strA
- String
要比較的第一個字串。
- strB
- String
要比較的第二個字串。
傳回
一個32位元帶符號的整數,表示兩個比較元之間的詞彙關係。
| 價值 | 條件 |
|---|---|
| 低於零 |
strA依排序順序排列。strB
|
| 零 |
strA與排序順序相同。strB
|
| 大於零 |
strA 依排序順序跟隨 strB 。
|
範例
以下範例將使用 Compare(String, String) 比較三組字串的方法。
// Create upper-case characters from their Unicode code units.
String stringUpper = "\x0041\x0042\x0043";
// Create lower-case characters from their Unicode code units.
String stringLower = "\x0061\x0062\x0063";
// Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower);
// Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0
? "true" : "false");
// The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
String.Compare(stringUpper, stringLower, true) == 0
? "true" : "false" );
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
open System
// Create upper-case characters from their Unicode code units.
let stringUpper = "\x0041\x0042\x0043"
// Create lower-case characters from their Unicode code units.
let stringLower = "\x0061\x0062\x0063"
// Display the strings.
printfn $"Comparing '{stringUpper}' and '{stringLower}':"
// Compare the uppercased strings the result is true.
printfn $"The Strings are equal when capitalized? %b{String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0}"
// The previous method call is equivalent to this Compare method, which ignores case.
printfn $"The Strings are equal when case is ignored? %b{String.Compare(stringUpper, stringLower, true) = 0}"
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
Public Module Example
Public Sub Main()
' Create upper-case characters from their Unicode code units.
Dim stringUpper As String = ChrW(&H41) + ChrW(&H42) + ChrW(&H43)
' Create lower-case characters from their Unicode code units.
Dim stringLower As String = ChrW(&H61) + ChrW(&H62) + ChrW(&H63)
' Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower)
' Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
If(String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0,
"true", "false"))
' The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
If(String.Compare(stringUpper, stringLower, true) = 0,
"true", "false"))
End Sub
End Module
' The example displays the following output:
' Comparing 'ABC' and 'abc':
' The Strings are equal when capitalized? true
' The Strings are equal when case is ignored? true
在以下範例中,該 ReverseStringComparer 類別示範如何用該 Compare 方法評估兩串字串。
using System;
using System.Text;
using System.Collections;
public class SamplesArrayList
{
public static void Main()
{
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("Eric");
myAL.Add("Mark");
myAL.Add("Lance");
myAL.Add("Rob");
myAL.Add("Kris");
myAL.Add("Brad");
myAL.Add("Kit");
myAL.Add("Bradley");
myAL.Add("Keith");
myAL.Add("Susan");
// Displays the properties and values of the ArrayList.
Console.WriteLine("Count: {0}", myAL.Count);
PrintValues("Unsorted", myAL);
myAL.Sort();
PrintValues("Sorted", myAL);
myAL.Sort(new ReverseStringComparer());
PrintValues("Reverse", myAL);
string[] names = (string[])myAL.ToArray(typeof(string));
}
public static void PrintValues(string title, IEnumerable myList)
{
Console.Write("{0,10}: ", title);
StringBuilder sb = new StringBuilder();
foreach (string s in myList)
{
sb.AppendFormat("{0}, ", s);
}
sb.Remove(sb.Length - 2, 2);
Console.WriteLine(sb);
}
}
public class ReverseStringComparer : IComparer
{
public int Compare(object? x, object? y)
{
string? s1 = x as string;
string? s2 = y as string;
//negate the return value to get the reverse order
return -String.Compare(s1, s2);
}
}
open System
open System.Text
open System.Collections.Generic
type ReverseStringComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
-String.Compare(x, y)
let printValues title (myList: #seq<string>) =
printf $"{title,10}: "
let sb = StringBuilder()
for s in myList do
sb.Append $"{s}, " |> ignore
sb.Remove(sb.Length - 2, 2) |> ignore
printfn $"{sb}"
// Creates and initializes a new ResizeArray.
let myAL = ResizeArray()
myAL.Add "Eric"
myAL.Add "Mark"
myAL.Add "Lance"
myAL.Add "Rob"
myAL.Add "Kris"
myAL.Add "Brad"
myAL.Add "Kit"
myAL.Add "Bradley"
myAL.Add "Keith"
myAL.Add "Susan"
// Displays the properties and values of the ArrayList.
printfn $"Count: {myAL.Count}"
printValues "Unsorted" myAL
myAL.Sort()
printValues "Sorted" myAL
myAL.Sort(ReverseStringComparer())
printValues "Reverse" myAL
Imports System.Text
Imports System.Collections
Public Class SamplesArrayList
Public Shared Sub Main()
Dim myAL As New ArrayList()
' Creates and initializes a new ArrayList.
myAL.Add("Eric")
myAL.Add("Mark")
myAL.Add("Lance")
myAL.Add("Rob")
myAL.Add("Kris")
myAL.Add("Brad")
myAL.Add("Kit")
myAL.Add("Bradley")
myAL.Add("Keith")
myAL.Add("Susan")
' Displays the properties and values of the ArrayList.
Console.WriteLine("Count: {0}", myAL.Count)
PrintValues("Unsorted", myAL)
myAL.Sort()
PrintValues("Sorted", myAL)
Dim comp as New ReverseStringComparer
myAL.Sort(comp)
PrintValues("Reverse", myAL)
Dim names As String() = CType(myAL.ToArray(GetType(String)), String())
End Sub
Public Shared Sub PrintValues(title As String, myList As IEnumerable)
Console.Write("{0,10}: ", title)
Dim sb As New StringBuilder()
Dim s As String
For Each s In myList
sb.AppendFormat("{0}, ", s)
Next s
sb.Remove(sb.Length - 2, 2)
Console.WriteLine(sb)
End Sub
End Class
Public Class ReverseStringComparer
Implements IComparer
Function Compare(x As Object, y As Object) As Integer implements IComparer.Compare
Dim s1 As String = CStr (x)
Dim s2 As String = CStr (y)
'negate the return value to get the reverse order
Return - [String].Compare(s1, s2)
End Function 'Compare
End Class
備註
比較利用當前文化獲取特定文化資訊,如字模規則及個別字元的字母順序。 例如,文化可以指定某些字元組合視為單一字元,或以特定方式比較大寫與小寫字元,或字元排序順序取決於前後的字元。
比較是使用單字排序規則進行的。 關於字、字串和序數排序的更多資訊,請參見 System.Globalization.CompareOptions。
警告
在比較字串時,你應該呼叫該 Compare(String, String, StringComparison) 方法,這需要你明確指定該方法所使用的字串比較類型。 如需詳細資訊,請參閱使用字串的最佳做法。
其中一個或兩個比較可以是 null。 根據定義,任何字串,包括空字串(“”),都比空參考大於空參考;而兩個空參考則彼此比較為相等。
當發現不等式或兩串字串都被比較時,比較即告終止。 然而,如果兩串的比較結果等於一個字串的末端,而另一串字串還有字元,則剩餘字元的字串被視為較大。 回傳值是最後一次比較的結果。
當比較受培養物特定套管規則影響時,可能會產生意想不到的結果。 例如,在土耳其語中,以下範例會得到錯誤的結果,因為土耳其語的檔案系統並未對「file」中的字母「i」使用語言大小寫規則。
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
用序數比較將路徑名稱與「檔案」進行比較。 正確的程式碼如下:
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
給呼叫者的注意事項
字元集包含可忽略的字元。 Compare(String, String)該方法在進行文化敏感比較時,並未考慮這些特徵。 例如,若以下程式碼運行於 .NET Framework 4 或更新版本,若能以文化敏感方式比較「animal」與「ani-mal」(使用軟連字號或 U+00AD),即可表示這兩個字串是等價的。
string s1 = "ani\u00ADmal";
string s2 = "animal";
Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
s1, s2, String.Compare(s1, s2));
// The example displays the following output:
// Comparison of 'ani-mal' and 'animal': 0
open System
let s1 = "ani\u00ADmal"
let s2 = "animal"
printfn $"Comparison of '{s1}' and '{s2}': {String.Compare(s1, s2)}"
// The example displays the following output:
// Comparison of 'ani-mal' and 'animal': 0
Module Example
Public Sub Main()
Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
Dim s2 As String = "animal"
Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
s1, s2, String.Compare(s1, s2))
End Sub
End Module
' The example displays the following output:
' Comparison of 'ani-mal' and 'animal': 0
要辨識字串比較中可忽略的字元,呼叫該 Compare(String, String, StringComparison) 方法並為參數提供 或 OrdinalOrdinalIgnoreCasecomparisonType 的值。