String.CompareOrdinal Метод
Определение
Перегрузки
CompareOrdinal(String, Int32, String, Int32, Int32) |
Сравнивает подстроки двух указанных объектов String, вычисляя числовые значения соответствующих объектов Char в каждой подстроке.Compares substrings of two specified String objects by evaluating the numeric values of the corresponding Char objects in each substring. |
CompareOrdinal(String, String) |
Сравнивает два указанных объекта String, оценивая числовые значения соответствующих объектов Char в каждой строке.Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string. |
CompareOrdinal(String, Int32, String, Int32, Int32)
public:
static int CompareOrdinal(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length);
public static int CompareOrdinal (string strA, int indexA, string strB, int indexB, int length);
static member CompareOrdinal : string * int * string * int * int -> int
Public Shared Function CompareOrdinal (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer) As Integer
Параметры
- strA
- String
Первая из сравниваемых строк.The first string to use in the comparison.
- indexA
- Int32
Начальный индекс подстроки в strA
.The starting index of the substring in strA
.
- strB
- String
Вторая из сравниваемых строк.The second string to use in the comparison.
- indexB
- Int32
Начальный индекс подстроки в strB
.The starting index of the substring in strB
.
- length
- Int32
Максимальное число сравниваемых знаков в подстроках.The maximum number of characters in the substrings to compare.
Возвращаемое значение
32-битовое целое число со знаком, выражающее лексическое отношение двух сравниваемых значений.A 32-bit signed integer that indicates the lexical relationship between the two comparands.
ЗначениеValue | УсловиеCondition |
---|---|
Меньше нуляLess than zero | Подстрока в strA меньше, чем подстрока в strB .The substring in strA is less than the substring in strB .
|
НульZero | Подстроки равны, или значение параметра length равно нулю.The substrings are equal, or length is zero.
|
Больше нуляGreater than zero | Подстрока в strA больше, чем подстрока в strB .The substring in strA is greater than the substring in strB .
|
Исключения
strA
не имеет значение null
, и значение indexA
больше strA
,Length.strA
is not null
and indexA
is greater than strA
.Length.
-или--or-
strB
не имеет значение null
, и значение indexB
больше strB
,Length.strB
is not null
and indexB
is greater than strB
.Length.
-или--or-
indexA
, indexB
или length
является отрицательным значением.indexA
, indexB
, or length
is negative.
Примеры
В следующем примере показано, CompareOrdinal как Compare использовать разные порядки сортировки.This following example demonstrates that CompareOrdinal and Compare use different sort orders.
using namespace System;
using namespace System::Globalization;
int main()
{
String^ strLow = "abc";
String^ strCap = "ABC";
String^ result = "equal to ";
int x = 0;
int pos = 1;
// The Unicode codepoint for 'b' is greater than the codepoint for 'B'.
x = String::CompareOrdinal( strLow, pos, strCap, pos, 1 );
if ( x < 0 )
result = "less than";
if ( x > 0 )
result = "greater than";
Console::WriteLine( "CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos );
Console::WriteLine( " '{0}' is {1} '{2}'", strLow[ pos ], result, strCap[ pos ] );
// In U.S. English culture, 'b' is linguistically less than 'B'.
x = String::Compare( strLow, pos, strCap, pos, 1, false, gcnew CultureInfo( "en-US" ) );
if ( x < 0 )
result = "less than";
else
if ( x > 0 )
result = "greater than";
Console::WriteLine( "Compare(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos );
Console::WriteLine( " '{0}' is {1} '{2}'", strLow[ pos ], result, strCap[ pos ] );
}
using System;
using System.Globalization;
class Test
{
public static void Main(String[] args)
{
String strLow = "abc";
String strCap = "ABC";
String result = "equal to ";
int x = 0;
int pos = 1;
// The Unicode codepoint for 'b' is greater than the codepoint for 'B'.
x = String.CompareOrdinal(strLow, pos, strCap, pos, 1);
if (x < 0) result = "less than";
if (x > 0) result = "greater than";
Console.WriteLine("CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]);
// In U.S. English culture, 'b' is linguistically less than 'B'.
x = String.Compare(strLow, pos, strCap, pos, 1, false, new CultureInfo("en-US"));
if (x < 0) result = "less than";
else if (x > 0) result = "greater than";
Console.WriteLine("Compare(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]);
}
}
Imports System.Globalization
Class Test
Public Shared Sub Main(args() As [String])
Dim strLow As [String] = "abc"
Dim strCap As [String] = "ABC"
Dim result As [String] = "equal to "
Dim x As Integer = 0
Dim pos As Integer = 1
' The Unicode codepoint for 'b' is greater than the codepoint for 'B'.
x = [String].CompareOrdinal(strLow, pos, strCap, pos, 1)
If x < 0 Then
result = "less than"
End If
If x > 0 Then
result = "greater than"
End If
' In U.S. English culture, 'b' is linguistically less than 'B'.
Console.WriteLine("CompareOrdinal(""{0}"".Chars({2}), ""{1}"".Chars({2})):", strLow, strCap, pos)
Console.WriteLine(" '{0}' is {1} '{2}'", strLow.Chars(pos), result, strCap.Chars(pos))
x = [String].Compare(strLow, pos, strCap, pos, 1, False, New CultureInfo("en-US"))
If x < 0 Then
result = "less than"
ElseIf x > 0 Then
result = "greater than"
End If
Console.WriteLine("Compare(""{0}"".Chars({2}), ""{1}"".Chars({2})):", strLow, strCap, pos)
Console.WriteLine(" '{0}' is {1} '{2}'", strLow.Chars(pos), result, strCap.Chars(pos))
End Sub
End Class
Комментарии
indexA
Параметры, indexB
и length
должны быть неотрицательными.The indexA
, indexB
, and length
parameters must be nonnegative.
Число сравниваемых символов равно меньшей длине меньшей длины strA
indexA
, длины strB
меньшего indexB
и length
.The number of characters compared is the lesser of the length of strA
less indexA
, the length of strB
less indexB
, and length
.
Этот метод выполняет сравнение с учетом регистра, используя правила сортировки по порядковому номеру.This method performs a case-sensitive comparison using ordinal sort rules. Дополнительные сведения о сортировке по словам, строкам и порядковым номерам см. в разделе System.Globalization.CompareOptions .For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. Чтобы выполнить сравнение без учета регистра с помощью правил сортировки по порядковому номеру, вызовите Compare(String, Int32, String, Int32, Int32, StringComparison) метод с comparisonType
аргументом, для которого задано значение StringComparison.OrdinalIgnoreCase .To perform a case-insensitive comparison using ordinal sort rules, call the Compare(String, Int32, String, Int32, Int32, StringComparison) method with the comparisonType
argument set to StringComparison.OrdinalIgnoreCase.
Так как CompareOrdinal(String, String) является статическим методом strA
и strB
может иметь значение null
.Because CompareOrdinal(String, String) is a static method, strA
and strB
can be null
. Если оба значения равны null
, метод возвращает 0 (нуль), который указывает, что strA
и strB
равны.If both values are null
, the method returns 0 (zero), which indicates that strA
and strB
are equal. Если только одно из значений равно null
, метод считает, что значение, отличное от NULL, больше.If only one of the values is null
, the method considers the non-null value to be greater.
См. также раздел
Применяется к
CompareOrdinal(String, String)
public:
static int CompareOrdinal(System::String ^ strA, System::String ^ strB);
public static int CompareOrdinal (string strA, string strB);
static member CompareOrdinal : string * string -> int
Public Shared Function CompareOrdinal (strA As String, strB As String) As Integer
Параметры
- strA
- String
Первая сравниваемая строка.The first string to compare.
- strB
- String
Вторая сравниваемая строка.The second string to compare.
Возвращаемое значение
Целое число, выражающее лексическое соотношение двух сравниваемых значений.An integer that indicates the lexical relationship between the two comparands.
ЗначениеValue | УсловиеCondition |
---|---|
Меньше нуляLess than zero | Значение strA меньше strB .strA is less than strB .
|
НульZero | Значения параметров strA и strB равны.strA and strB are equal.
|
Больше нуля.Greater than zero | Значение strA больше значения strB .strA is greater than strB .
|
Примеры
В следующем примере выполняется и порядковое сравнение двух строк, которые различаются только регистром.The following example performs and ordinal comparison of two strings that only differ in case.
// Sample for String::CompareOrdinal(String, String)
using namespace System;
int main()
{
String^ str1 = "ABCD";
String^ str2 = "abcd";
String^ str;
int result;
Console::WriteLine();
Console::WriteLine( "Compare the numeric values of the corresponding Char objects in each string." );
Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
result = String::CompareOrdinal( str1, str2 );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
Console::Write( "String '{0}' is ", str1 );
Console::Write( "{0} ", str );
Console::WriteLine( "String '{0}'.", str2 );
}
/*
This example produces the following results:
Compare the numeric values of the corresponding Char objects in each string.
str1 = 'ABCD', str2 = 'abcd'
String 'ABCD' is less than String 'abcd'.
*/
// Sample for String.CompareOrdinal(String, String)
using System;
class Sample {
public static void Main() {
String str1 = "ABCD";
String str2 = "abcd";
String str;
int result;
Console.WriteLine();
Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string.");
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.CompareOrdinal(str1, str2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("String '{0}' is ", str1);
Console.Write("{0} ", str);
Console.WriteLine("String '{0}'.", str2);
}
}
/*
This example produces the following results:
Compare the numeric values of the corresponding Char objects in each string.
str1 = 'ABCD', str2 = 'abcd'
String 'ABCD' is less than String 'abcd'.
*/
' Sample for String.CompareOrdinal(String, String)
Class Sample
Public Shared Sub Main()
Dim str1 As [String] = "ABCD"
Dim str2 As [String] = "abcd"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string.")
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
result = [String].CompareOrdinal(str1, str2)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("String '{0}' is ", str1)
Console.Write("{0} ", str)
Console.WriteLine("String '{0}'.", str2)
End Sub
End Class
'
'This example produces the following results:
'
'Compare the numeric values of the corresponding Char objects in each string.
'str1 = 'ABCD', str2 = 'abcd'
'String 'ABCD' is less than String 'abcd'.
'
Комментарии
Этот метод выполняет сравнение с учетом регистра, используя правила сортировки по порядковому номеру.This method performs a case-sensitive comparison using ordinal sort rules. Дополнительные сведения о сортировке по словам, строкам и порядковым номерам см. в разделе System.Globalization.CompareOptions .For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. Чтобы выполнить сравнение без учета регистра с помощью правил сортировки по порядковому номеру, вызовите Compare(String, String, StringComparison) метод с comparisonType
аргументом, для которого задано значение StringComparison.OrdinalIgnoreCase .To perform a case-insensitive comparison using ordinal sort rules, call the Compare(String, String, StringComparison) method with the comparisonType
argument set to StringComparison.OrdinalIgnoreCase.
Так как CompareOrdinal(String, String) является статическим методом strA
и strB
может иметь значение null
.Because CompareOrdinal(String, String) is a static method, strA
and strB
can be null
. Если оба значения равны null
, метод возвращает 0 (нуль), который указывает, что strA
и strB
равны.If both values are null
, the method returns 0 (zero), which indicates that strA
and strB
are equal. Если только одно из значений равно null
, метод считает, что значение, отличное от NULL, больше.If only one of the values is null
, the method considers the non-null value to be greater.