String.CompareOrdinal Método

Definição

Compara dois objetos String avaliando os valores numéricos dos objetos Char correspondentes em cada cadeia de caracteres.

Sobrecargas

CompareOrdinal(String, String)

Compara dois objetos String especificados avaliando os valores numéricos dos objetos Char correspondentes em cada cadeia de caracteres.

CompareOrdinal(String, Int32, String, Int32, Int32)

Compara subcadeias de caracteres de dois objetos String especificados avaliando os valores numéricos dos objetos Char correspondentes em cada subcadeia de caracteres.

CompareOrdinal(String, String)

Origem:
String.Comparison.cs
Origem:
String.Comparison.cs
Origem:
String.Comparison.cs

Compara dois objetos String especificados avaliando os valores numéricos dos objetos Char correspondentes em cada cadeia de caracteres.

public:
 static int CompareOrdinal(System::String ^ strA, System::String ^ strB);
public static int CompareOrdinal (string strA, 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

Parâmetros

strA
String

A primeira cadeia de caracteres a ser comparada.

strB
String

A segunda cadeia de caracteres a ser comparada.

Retornos

Um número inteiro que indica a relação lexical entre os dois termos de comparação.

Valor Condição
Menor que zerostrA é menor que strB.
ZerostrA e strB são iguais.
Maior que zerostrA é maior que strB.

Exemplos

O exemplo a seguir executa uma comparação ordinal de duas cadeias de caracteres que diferem apenas no caso.

// 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)
open System

let str1 = "ABCD"
let str2 = "abcd"

printfn "\nCompare the numeric values of the corresponding Char objects in each string."
printfn $"str1 = '{str1}', str2 = '{str2}'"
let result = String.CompareOrdinal(str1, str2)
let str = if result < 0 then "less than" elif result > 0 then "greater than" else "equal to"
printf $"String '{str1}' is "
printf $"{str} "
printfn $"String '{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'.
'

Comentários

Esse método executa uma comparação que diferencia maiúsculas de minúsculas usando regras de classificação ordinal. Para obter mais informações sobre a palavra, a cadeia de caracteres e os tipos ordinais, consulte System.Globalization.CompareOptions. Para executar uma comparação que não diferencia maiúsculas de minúsculas usando regras de classificação ordinal, chame o Compare(String, String, StringComparison) método com o comparisonType argumento definido como StringComparison.OrdinalIgnoreCase.

Porque CompareOrdinal(String, String) é um método strA estático e strB pode ser null. Se ambos os valores forem null, o método retornará 0 (zero), o que indica que strA e strB são iguais. Se apenas um dos valores for null, o método considerará o valor não nulo maior.

Confira também

Aplica-se a

CompareOrdinal(String, Int32, String, Int32, Int32)

Origem:
String.Comparison.cs
Origem:
String.Comparison.cs
Origem:
String.Comparison.cs

Compara subcadeias de caracteres de dois objetos String especificados avaliando os valores numéricos dos objetos Char correspondentes em cada subcadeia de caracteres.

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

Parâmetros

strA
String

A primeira cadeia de caracteres a ser usada na comparação.

indexA
Int32

O índice inicial da subcadeia de caracteres em strA.

strB
String

A segunda cadeia de caracteres a ser usada na comparação.

indexB
Int32

O índice inicial da subcadeia de caracteres em strB.

length
Int32

O número máximo de caracteres nas subcadeias de caracteres a serem comparadas.

Retornos

Um inteiro assinado de 32 bits que indica a relação léxica entre os dois termos de comparação.

Valor Condição
Menor que zero A subcadeia de caracteres em strA é menor que a subcadeia de caracteres em strB.
Zero As subcadeias de caracteres são iguais ou length é zero.
Maior que zero A subcadeia de caracteres em strA é maior que a subcadeia de caracteres em strB.

Exceções

strA não é null e indexA é maior que strA.Length.

- ou -

strB não é null e indexB é maior que strB.Length.

- ou -

indexA, indexB ou length é negativo.

Exemplos

Este exemplo a seguir demonstra isso CompareOrdinal e Compare usa ordens de classificação diferentes.

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]);
    }
}
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    let strLow = "abc"
    let strCap = "ABC"
    let result = "equal to "
    let pos = 1

    // The Unicode codepoint for 'b' is greater than the codepoint for 'B'.
    let x = String.CompareOrdinal(strLow, pos, strCap, pos, 1)
    let result =
        if x < 0 then "less than"
        elif x > 0 then "greater than"
        else "equal to"
    printfn $"CompareOrdinal(\"{strLow}\"[{pos}], \"{strCap}\"[{pos}]):"
    printfn $"   '{strLow[pos]}' is {result} '{strCap[pos]}'"

    // In U.S. English culture, 'b' is linguistically less than 'B'.
    let x = String.Compare(strLow, pos, strCap, pos, 1, false, new CultureInfo("en-US"))
    let result =
        if x < 0 then "less than"
        elif x > 0 then "greater than"
        else "equal to"
    printfn $"Compare(\"{strLow}\"[{pos}], \"{strCap}\"[{pos}]):"
    printfn $"   '{strLow[pos]}' is {result} '{strCap[pos]}'"
    0
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

Comentários

Os parâmetros indexA, indexB e length devem ser não negativos.

O número de caracteres comparados é o menor do comprimento de strA menos indexA, o comprimento de strB menos indexBe length.

Esse método executa uma comparação que diferencia maiúsculas de minúsculas usando regras de classificação ordinal. Para obter mais informações sobre a palavra, a cadeia de caracteres e os tipos ordinais, consulte System.Globalization.CompareOptions. Para executar uma comparação que não diferencia maiúsculas de minúsculas usando regras de classificação ordinal, chame o Compare(String, Int32, String, Int32, Int32, StringComparison) método com o comparisonType argumento definido como StringComparison.OrdinalIgnoreCase.

Porque CompareOrdinal(String, String) é um método strA estático e strB pode ser null. Se ambos os valores forem null, o método retornará 0 (zero), o que indica que strA e strB são iguais. Se apenas um dos valores for null, o método considerará o valor não nulo maior.

Confira também

Aplica-se a