String.Compare 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
比较两个指定的 String 对象,并返回一个指示二者在排序顺序中的相对位置的整数。
重载
Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) |
对两个指定 String 对象的子字符串进行比较,使用指定的比较选项和区域性特定的信息来影响比较,并返回一个整数,该整数指示这两个子字符串在排序顺序中的关系。 |
Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) |
比较两个指定的 String 对象(其中忽略或考虑其大小写,并使用区域性特定的信息干预比较),并返回一个整数,指示二者在排序顺序中的相对位置。 |
Compare(String, Int32, String, Int32, Int32, StringComparison) |
使用指定的规则比较两个指定的 String 对象的子字符串,并返回一个整数,指示二者在排序顺序中的相对位置。 |
Compare(String, Int32, String, Int32, Int32, Boolean) |
比较两个指定的 String 对象的子字符串(忽略或考虑其大小写),并返回一个整数,指示二者在排序顺序中的相对位置。 |
Compare(String, Int32, String, Int32, Int32) |
比较两个指定的 String 对象的子字符串,并返回一个指示二者在排序顺序中的相对位置的整数。 |
Compare(String, String) |
比较两个指定的 String 对象,并返回一个指示二者在排序顺序中的相对位置的整数。 |
Compare(String, String, Boolean, CultureInfo) |
比较两个指定的 String 对象(其中忽略或考虑其大小写,并使用区域性特定的信息干预比较),并返回一个整数,指示二者在排序顺序中的相对位置。 |
Compare(String, String, StringComparison) |
使用指定的规则比较两个指定的 String 对象,并返回一个整数,指示二者在排序顺序中的相对位置。 |
Compare(String, String, Boolean) |
比较两个指定的 String 对象(其中忽略或考虑其大小写),并返回一个整数,指示二者在排序顺序中的相对位置。 |
Compare(String, String, CultureInfo, CompareOptions) |
对两个指定的 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
为负数。
- 或 -
strA
或 strB
为 null
,并且 length
大于零。
示例
下面的示例使用 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 方法比较两个人的名字。 然后,它按字母顺序列出它们。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
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
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
注解
要比较的子字符串从 位置 strA
开始, indexA
在 位置 strB
开始 indexB
。 第一个子字符串的长度是减去 strA
的长度 indexA
。 第二个子字符串的长度是减去 strB
的长度 indexB
。
要比较的字符数是两个子字符串 和 的长度中较小 length
者。 、 indexA
indexB
和 length
参数必须无要求。
比较使用 culture
参数获取区域性特定信息,例如大小写规则和单个字符的字母顺序。 例如,特定区域性可以指定将字符的某些组合视为单个字符、以特定方式比较大写字符和小写字符,或指定字符的排序顺序取决于它之前或之后的字符。
注意
Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)方法主要用于排序或按字母顺序排序操作。 当方法调用的主要用途是确定两个子字符串是否等效时,不应使用 (也就是说,当方法调用的目的是测试返回值零值时) 。 若要确定两个字符串是否等效,请调用 Equals 方法。
和 的一个或 strA
两 strB
个可以是 null
。 根据定义,任何字符串(包括 String.Empty )都比较大于 null 引用,两个 null 引用相互比较相等。
可通过 参数进一步指定比较 options
,该参数由 枚举的一个或多个 System.Globalization.CompareOptions 成员组成。 但是,由于此方法的目的是进行区分区域性的字符串比较,因此 和 CompareOptions.Ordinal CompareOptions.OrdinalIgnoreCase 值不起作用。
当发现不相等或已比较两个子字符串时,比较将终止。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串有剩余字符,则剩余字符的字符串将被视为更大的字符串。 返回值是上次执行的比较的结果。
调用方说明
字符集包括可忽略字符。 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)方法执行语言或区分区域性的比较时不考虑这些字符。 若要识别比较中的可忽略字符,请为 Ordinal 参数提供 或 OrdinalIgnoreCase options
值。
另请参阅
适用于
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
为负数。
- 或 -
strA
或 strB
为 null
,并且 length
大于零。
示例
下面的示例比较两个使用不同区域性的子字符串,并忽略子字符串的大小写。 区域性的选择会影响字母"I"的比较。
// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using namespace System;
using namespace System::Globalization;
int 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, gcnew CultureInfo( "tr-TR" ) );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"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) ? (String^)"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)
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)
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'.
'
注解
要比较的子字符串从 开始,在 中 strA
indexA
从 strB
开始 indexB
。 和 indexA
indexB
都从零开始;也就是说,和 中的第一个字符位于位置 strA
strB
零,而不是位置 1。 第一个子字符串的长度等于减 strA
indexA
1 的长度。 第二个子字符串的长度等于减 strB
indexB
1 的长度。
要比较的字符数是两个子字符串 和 的长度中较小 length
者。 、 indexA
indexB
和 length
参数必须无要求。
比较使用 culture
参数获取区域性特定信息,例如大小写规则和单个字符的字母顺序。 例如,区域性可以指定将字符的某些组合视为单个字符,或者以特定方式比较大写和小写字符,或者字符的排序顺序取决于它之前或之后的字符。
比较是使用单词排序规则执行的。 有关单词、字符串和序号排序详细信息,请参阅 System.Globalization.CompareOptions 。
一个或两个比较项可以是 null
。 根据定义,任何字符串(包括空字符串 ("") )都大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或已比较两个子字符串时,比较将终止。 但是,如果两个字符串的比较等于一个字符串的末尾,另一个字符串有剩余字符,则剩余字符的字符串被视为较大。 返回值是上次执行的比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外结果。 例如,在土耳其语中,以下示例生成错误的结果,因为土耳其语中的文件系统不会对"file"中的字母"i"使用语言大小写规则。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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
使用序号比较将路径名称与"file"进行比较。 要执行此操作的正确代码如下所示:
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
return (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 或 OrdinalIgnoreCase options
值。
另请参阅
适用于
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
为负数。
- 或 -
indexA
或 indexB
为 null
,并且 length
大于零。
comparisonType
不是 StringComparison 值。
示例
下面的示例比较两个子字符串。
// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main()
{
// 0123456
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) ? (String^)"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'.
*/
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'.
*/
' 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'.
'
注解
要比较的子字符串 strA
在 indexA
和中的开始 strB
处 indexB
。 indexA
和 indexB
都是从零开始的; 即,和中的第一个字符位于 strA
strB
位置零,而不是位置1。 第一个子字符串的长度等于 strA
减号 indexA
加1的长度。 第二个子字符串的长度等于 strB
减号 indexB
加1。
要比较的字符数是两个子字符串的长度中较小的一个和 length
。 indexA
、 indexB
和 length
参数必须为非负。
comparisonType
参数指示比较应使用当前的或固定的区域性,是接受还是忽略比较规则的大小写,还是使用 word (区分区域性的) 或序号 (不区分区域性的) 排序规则。
其中一个或两个比较字可以为 null
。 按照定义,包含空字符串 ( "" ) 中的任何字符串都会比较大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或比较两个子字符串时,将终止比较。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串还剩个字符,则包含剩余字符的字符串将被视为更大的字符串。 返回值是执行的最后一次比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外的结果。 例如,在土耳其语中,以下示例产生了错误的结果,因为土耳其语中的文件系统不会将语言大小写规则用于 "file" 中的字母 "i"。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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
使用序号比较将路径名称与 "file" 进行比较。 要执行此操作,正确的代码如下所示:
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
return (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 参数提供 或 OrdinalIgnoreCase comparisonType
值。
另请参阅
适用于
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
为负数。
- 或 -
indexA
或 indexB
为 null
,并且 length
大于零。
示例
下面的示例对两个仅大小写不同的子字符串执行两次比较。 第一个比较忽略大小写,第二个比较考虑用例。
// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean)
using namespace System;
int 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:" );
result = String::Compare( str1, 2, str2, 2, 2, true );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"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) ? (String^)"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'.
*/
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'.
*/
' 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'.
'
注解
要比较的子字符串在中的开始 strA
indexA
,位于中 strB
indexB
。 indexA
和 indexB
都是从零开始的; 即,和中的第一个字符位于 strA
strB
位置零。 第一个子字符串的长度等于 strA
减号 indexA
加1的长度。 第二个子字符串的长度等于 strB
减号 indexB
加1。
要比较的字符数是两个子字符串的长度中较小的一个和 length
。 indexA
、 indexB
和 length
参数必须为非负。
比较使用当前区域性来获取特定于区域性的信息,如大小写规则和单个字符的字母顺序。 例如,区域性可以指定将某些字符组合视为单个字符,或以特定方式比较大写和小写字符,或字符的排序顺序取决于其前面或后面的字符。
使用字词排序规则执行比较。 有关 word、字符串和顺序排序的详细信息,请参阅 System.Globalization.CompareOptions 。
警告
在比较字符串时,应调用 Compare(String, Int32, String, Int32, Int32, StringComparison) 方法,这要求您显式指定方法使用的字符串比较的类型。 有关详细信息,请参阅有关使用字符串的最佳实践。
其中一个或两个比较字可以为 null
。 按照定义,包含空字符串 ( "" ) 中的任何字符串都会比较大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或比较两个子字符串时,将终止比较。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串还剩个字符,则包含剩余字符的字符串将被视为更大的字符串。 返回值是执行的最后一次比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外的结果。 例如,在土耳其语中,以下示例产生了错误的结果,因为土耳其语中的文件系统不会将语言大小写规则用于 "file" 中的字母 "i"。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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);
}
static bool IsFileURI(String path)
{
return (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 参数提供值或 OrdinalIgnoreCase comparisonType
。
另请参阅
适用于
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
为负数。
- 或 -
indexA
或 indexB
为 null
,并且 length
大于零。
示例
下面的示例比较两个子字符串。
// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main()
{
// 0123456
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) ? (String^)"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'.
*/
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'.
*/
' 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'.
'
注解
要比较的子字符串 strA
在 indexA
和中的开始 strB
处 indexB
。 indexA
和 indexB
都是从零开始的; 即,和中的第一个字符位于 strA
strB
位置零。 第一个子字符串的长度等于 strA
减号 indexA
加1的长度。 第二个子字符串的长度等于 strB
减号 indexB
加1。
要比较的字符数是两个子字符串的长度中较小的一个和 length
。 indexA
、 indexB
和 length
参数必须为非负。
比较使用当前区域性来获取特定于区域性的信息,如大小写规则和单个字符的字母顺序。 例如,区域性可以指定将某些字符组合视为单个字符,或以特定方式比较大写和小写字符,或字符的排序顺序取决于其前面或后面的字符。
使用字词排序规则执行比较。 有关 word、字符串和顺序排序的详细信息,请参阅 System.Globalization.CompareOptions 。
警告
在比较字符串时,应调用 Compare(String, Int32, String, Int32, Int32, StringComparison) 方法,这要求您显式指定方法使用的字符串比较的类型。 有关详细信息,请参阅有关使用字符串的最佳实践。
其中一个或两个比较字可以为 null
。 按照定义,包含空字符串 ( "" ) 中的任何字符串都会比较大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或比较两个子字符串时,将终止比较。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串还剩个字符,则包含剩余字符的字符串将被视为更大的字符串。 返回值是执行的最后一次比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外的结果。 例如,在土耳其语中,以下示例产生了错误的结果,因为土耳其语中的文件系统不会将语言大小写规则用于 "file" 中的字母 "i"。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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
使用序号比较将路径名称与 "file" 进行比较。 要执行此操作,正确的代码如下所示:
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
return (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 参数提供值或 OrdinalIgnoreCase comparisonType
。
另请参阅
适用于
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) 方法来比较三组字符串。
using namespace System;
void main()
{
// 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
// 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
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 namespace System;
using namespace System::Text;
using namespace System::Collections;
ref class ReverseStringComparer: public IComparer
{
public:
virtual int Compare( Object^ x, Object^ y )
{
String^ s1 = dynamic_cast<String^>(x);
String^ s2 = dynamic_cast<String^>(y);
//negate the return value to get the reverse order
return -String::Compare( s1, s2 );
}
};
void PrintValues( String^ title, IEnumerable^ myList )
{
Console::Write( "{0,10}: ", title );
StringBuilder^ sb = gcnew StringBuilder;
{
IEnumerator^ en = myList->GetEnumerator();
String^ s;
while ( en->MoveNext() )
{
s = en->Current->ToString();
sb->AppendFormat( "{0}, ", s );
}
}
sb->Remove( sb->Length - 2, 2 );
Console::WriteLine( sb );
}
void main()
{
// Creates and initializes a new ArrayList.
ArrayList^ myAL = gcnew 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.ToString() );
PrintValues( "Unsorted", myAL );
myAL->Sort();
PrintValues( "Sorted", myAL );
myAL->Sort( gcnew ReverseStringComparer );
PrintValues( "Reverse", myAL );
array<String^>^names = dynamic_cast<array<String^>^>(myAL->ToArray( String::typeid ));
}
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);
}
}
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
注解
比较使用当前区域性来获取特定于区域性的信息,如大小写规则和单个字符的字母顺序。 例如,区域性可以指定将某些字符组合视为单个字符,或以特定方式比较大写和小写字符,或字符的排序顺序取决于其前面或后面的字符。
使用字词排序规则执行比较。 有关 word、字符串和顺序排序的详细信息,请参阅 System.Globalization.CompareOptions 。
警告
在比较字符串时,应调用 Compare(String, String, StringComparison) 方法,这要求您显式指定方法使用的字符串比较的类型。 有关详细信息,请参阅有关使用字符串的最佳实践。
其中一个或两个比较字可以为 null
。 按照定义,包含空字符串 ( "" ) 中的任何字符串都会比较大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或已比较两个字符串时,将终止比较。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串还剩个字符,则包含剩余字符的字符串将被视为更大的字符串。 返回值是执行的最后一次比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外的结果。 例如,在土耳其语中,以下示例产生了错误的结果,因为土耳其语中的文件系统不会将语言大小写规则用于 "file" 中的字母 "i"。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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
使用序号比较将路径名称与 "file" 进行比较。 要执行此操作,正确的代码如下所示:
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
return (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 或更高版本上运行,则使用软连字符 (使用 "ani" 的 "动物" 比较区分区域性的比较或 U + 00AD) 指示这两个字符串是等效的。
::: code language = "csharp" source = "~/samples/snippets/csharp/VS_Snippets_CLR_System/system。Compare21 "id =" Snippet21 ":::::: code language =" vb "source =" ~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system。Compare21 "id =" Snippet21 ":::
若要在字符串比较中识别可忽略字符,请调用 Compare(String, String, StringComparison) 方法,并 Ordinal 为参数提供或的值 OrdinalIgnoreCase comparisonType
。
另请参阅
适用于
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"。
using namespace System;
using namespace System::Globalization;
String^ symbol( int r )
{
String^ s = "=";
if ( r < 0 )
s = "<";
else
if ( r > 0 )
s = ">";
return s;
}
int main()
{
String^ str1 = "change";
String^ str2 = "dollar";
String^ relation = nullptr;
relation = symbol( String::Compare( str1, str2, false, gcnew CultureInfo( "en-US" ) ) );
Console::WriteLine( "For en-US: {0} {1} {2}", str1, relation, str2 );
relation = symbol( String::Compare( str1, str2, false, gcnew CultureInfo( "cs-CZ" ) ) );
Console::WriteLine( "For cs-CZ: {0} {1} {2}", str1, relation, str2 );
}
/*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*/
public static void Main()
{
String str1 = "change";
String str2 = "dollar";
String relation = null;
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
*/
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
参数获取特定于区域性的信息,如大小写规则和单个字符的字母顺序。 例如,区域性可以指定将某些字符组合视为单个字符,或以特定方式比较大写和小写字符,或字符的排序顺序取决于其前面或后面的字符。
使用字词排序规则执行比较。 有关 word、字符串和顺序排序的详细信息,请参阅 System.Globalization.CompareOptions 。
其中一个或两个比较字可以为 null
。 按照定义,包含空字符串 ( "" ) 中的任何字符串都会比较大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或已比较两个字符串时,将终止比较。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串还剩个字符,则包含剩余字符的字符串将被视为更大的字符串。 返回值是执行的最后一次比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外的结果。 例如,在土耳其语中,以下示例产生了错误的结果,因为土耳其语中的文件系统不会将语言大小写规则用于 "file" 中的字母 "i"。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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
使用序号比较将路径名称与 "file" 进行比较。 要执行此操作,正确的代码如下所示:
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
return (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 或更高版本上运行,则使用软连字符 (不区分大小写的 "动物" 比较使用软连字符,或使用固定区域性的 U + 00AD) 指示这两个字符串是等效的。
::: code language = "csharp" source = "~/samples/snippets/csharp/VS_Snippets_CLR_System/system。Compare23 "id =" Snippet23 ":::::: code language =" vb "source =" ~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system。Compare23 "id =" Snippet23 ":::
若要在字符串比较中识别可忽略字符,请调用 Compare(String, String, CultureInfo, CompareOptions) 方法,并 Ordinal 为参数提供或的值 OrdinalIgnoreCase options
。
另请参阅
- 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 namespace System;
using namespace System::Threading;
void Test(int testStringIndex, int searchStringIndex,
StringComparison comparison, array<String^>^ testI,
array<String^>^ testNames)
{
String^ resultFormat = "{0} is {1} {2}";
String^ resultString = "equal to";
int comparisonValue = 0;
comparisonValue = String::Compare(testI[testStringIndex],
testI[searchStringIndex], comparison);
if (comparisonValue < 0)
{
resultString = "less than";
}
else if (comparisonValue > 0)
{
resultString = "greater than";
}
Console::WriteLine(resultFormat, testNames[testStringIndex], resultString,
testNames[searchStringIndex]);
}
int main()
{
String^ introMessage =
"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.)
array<String^>^ letterVariation = gcnew array<String^>(3);
// LATIN SMALL LETTER I (U+0069)
letterVariation[0] = "i";
// LATIN SMALL LETTER DOTLESS I (U+0131)
letterVariation[1] = L"\u0131";
// LATIN CAPITAL LETTER I (U+0049)
letterVariation[2] = "I";
array<String^>^ unicodeNames = {
"LATIN SMALL LETTER I (U+0069)",
"LATIN SMALL LETTER DOTLESS I (U+0131)",
"LATIN CAPITAL LETTER I (U+0049)"};
array<StringComparison>^ comparisonValues = {
StringComparison::CurrentCulture,
StringComparison::CurrentCultureIgnoreCase,
StringComparison::InvariantCulture,
StringComparison::InvariantCultureIgnoreCase,
StringComparison::Ordinal,
StringComparison::OrdinalIgnoreCase};
Console::Clear();
Console::WriteLine(introMessage);
// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
Console::WriteLine("The current culture is {0}.{1}",
Thread::CurrentThread->CurrentCulture->Name, Environment::NewLine);
// Determine the relative sort order of three versions of the letter I.
for each (StringComparison stringCmp in comparisonValues)
{
Console::WriteLine("StringComparison.{0}:", stringCmp);
// LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I
// (U+0131)
Test(0, 1, stringCmp, letterVariation, unicodeNames);
// LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
Test(0, 2, stringCmp, letterVariation, unicodeNames);
// LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I
// (U+0049)
Test(1, 2, stringCmp, letterVariation, unicodeNames);
Console::WriteLine();
}
}
/*
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.
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.
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
参数指示比较应使用当前的或固定的区域性,是接受还是忽略比较规则的大小写,还是使用 word (区分区域性的) 或序号 (不区分区域性的) 排序规则。
其中一个或两个比较字可以为 null
。 按照定义,包含空字符串 ( "" ) 中的任何字符串都会比较大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或已比较两个字符串时,将终止比较。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串还剩个字符,则包含剩余字符的字符串将被视为更大的字符串。 返回值是执行的最后一次比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外的结果。 例如,在土耳其语中,以下示例产生了错误的结果,因为土耳其语中的文件系统不会将语言大小写规则用于 "file" 中的字母 "i"。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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
使用序号比较将路径名称与 "file" 进行比较。 要执行此操作,正确的代码如下所示:
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
return (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 为参数提供值或 OrdinalIgnoreCase comparisonType
。
另请参阅
适用于
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 比较字符串时使用或。
using namespace System;
void main()
{
// 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
// 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
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
注解
比较使用当前区域性来获取特定于区域性的信息,如大小写规则和单个字符的字母顺序。 例如,区域性可以指定将某些字符组合视为单个字符,或以特定方式比较大写和小写字符,或字符的排序顺序取决于其前面或后面的字符。
使用字词排序规则执行比较。 有关 word、字符串和顺序排序的详细信息,请参阅 System.Globalization.CompareOptions 。
警告
在比较字符串时,应调用 Compare(String, String, StringComparison) 方法,这要求您显式指定方法使用的字符串比较的类型。 有关详细信息,请参阅有关使用字符串的最佳实践。
其中一个或两个比较字可以为 null
。 按照定义,包含空字符串 ( "" ) 中的任何字符串都会比较大于 null 引用;和两个 null 引用的比较结果相等。
当发现不相等或已比较两个字符串时,将终止比较。 但是,如果两个字符串的比较结果等于一个字符串的末尾,而另一个字符串还剩个字符,则包含剩余字符的字符串将被视为更大的字符串。 返回值是执行的最后一次比较的结果。
当比较受区域性特定的大小写规则影响时,可能会出现意外的结果。 例如,在土耳其语中,以下示例产生了错误的结果,因为土耳其语中的文件系统不会将语言大小写规则用于 "file" 中的字母 "i"。
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
return (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
使用序号比较将路径名称与 "file" 进行比较。 要执行此操作,正确的代码如下所示:
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
return (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)当方法执行区分区域性的比较时,它不会考虑此类字符。 例如,如果以下代码在 .NET Framework 4 或更高版本上运行,则使用软连字符的 "动物" (区分区域性、不区分大小写的 "动物" 比较,或使用 U + 00AD) 指示这两个字符串是等效的。
::: code language = "csharp" source = "~/samples/snippets/csharp/VS_Snippets_CLR_System/system。Compare22 "id =" Snippet22 ":::::: code language =" vb "source =" ~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system。Compare22 "id =" Snippet22 ":::
若要在字符串比较中识别可忽略字符,请调用 Compare(String, String, StringComparison) 方法,并 Ordinal 为参数提供或的值 OrdinalIgnoreCase comparisonType
。
另请参阅
适用于
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 namespace System;
using namespace System::Globalization;
public ref class Example
{
public:
static void Main()
{
String^ string1 = "brother";
String^ string2 = "Brother";
String^ relation;
int result;
// Cultural (linguistic) comparison.
result = String::Compare(string1, string2, gcnew 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, gcnew 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);
}
};
int main()
{
Example::Main();
}
// The example produces the following output:
// 'brother' comes before 'Brother'.
// 'brother' is the same as 'Brother'.
// 'brother' comes after 'Brother'.
using System;
using System.Globalization;
public class Example
{
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'.
}
}
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) 方法主要用于排序或 alphabetizing 操作。 当方法调用的主要目的是确定两个字符串是否等效时,不应使用此方法,即,当方法调用的目的是测试零) 的返回值时 (。 若要确定两个字符串是否相等,请调用 Equals 方法。
可以通过参数进一步指定比较,该 options
参数由一个或多个枚举成员组成 CompareOptions 。 但是,由于此方法的目的是执行区分区域性的字符串比较, CompareOptions.Ordinal 因此和 CompareOptions.OrdinalIgnoreCase 值不起作用。
两者或两个比较字都可以 null
。 按照定义,任何字符串(包括 String.Empty 、)比较大于 null 引用,而两个 null 引用的比较结果相等。
当发现不相等或已比较两个字符串时,将终止比较。 但是,如果两个字符串的比较结果与一个字符串的末尾相等,而另一个字符串还剩个字符,则将剩余字符视为更大的字符串。
调用方说明
字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 Compare(String, String, CultureInfo, CompareOptions)当方法执行区分区域性的比较时,它不会考虑此类字符。 若要在比较中识别可忽略字符,请 Ordinal 为参数提供值或 OrdinalIgnoreCase options
。