CompareInfo.Compare CompareInfo.Compare CompareInfo.Compare CompareInfo.Compare Method

Definição

Compara duas cadeias de caracteres.Compares two strings.

Sobrecargas

Compare(String, String) Compare(String, String) Compare(String, String) Compare(String, String)

Compara duas cadeias de caracteres.Compares two strings.

Compare(String, String, CompareOptions) Compare(String, String, CompareOptions) Compare(String, String, CompareOptions) Compare(String, String, CompareOptions)

Compara duas cadeias de caracteres usando o valor CompareOptions especificado.Compares two strings using the specified CompareOptions value.

Compare(String, Int32, String, Int32) Compare(String, Int32, String, Int32) Compare(String, Int32, String, Int32) Compare(String, Int32, String, Int32)

Compara a seção final de uma cadeia de caracteres com a seção final de outra.Compares the end section of a string with the end section of another string.

Compare(String, Int32, String, Int32, CompareOptions) Compare(String, Int32, String, Int32, CompareOptions) Compare(String, Int32, String, Int32, CompareOptions) Compare(String, Int32, String, Int32, CompareOptions)

Compara a seção final de uma cadeia de caracteres com a seção final de outra usando o valor de CompareOptions especificado.Compares the end section of a string with the end section of another string using the specified CompareOptions value.

Compare(String, Int32, Int32, String, Int32, Int32) Compare(String, Int32, Int32, String, Int32, Int32) Compare(String, Int32, Int32, String, Int32, Int32) Compare(String, Int32, Int32, String, Int32, Int32)

Compara uma seção de uma cadeia de caracteres com uma seção de outra.Compares a section of one string with a section of another string.

Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions)

Compara uma seção de uma cadeia de caracteres com uma seção de outra usando o valor de CompareOptions especificado.Compares a section of one string with a section of another string using the specified CompareOptions value.

Compare(String, String) Compare(String, String) Compare(String, String) Compare(String, String)

Compara duas cadeias de caracteres.Compares two strings.

public:
 virtual int Compare(System::String ^ string1, System::String ^ string2);
public virtual int Compare (string string1, string string2);
abstract member Compare : string * string -> int
override this.Compare : string * string -> int
Public Overridable Function Compare (string1 As String, string2 As String) As Integer

Parâmetros

string1
String String String String

A primeira cadeia de caracteres a ser comparada.The first string to compare.

string2
String String String String

A segunda cadeia de caracteres a ser comparada.The second string to compare.

Retornos

Um inteiro com sinal de 32 bits que indica a relação léxica entre os dois termos de comparação.A 32-bit signed integer indicating the lexical relationship between the two comparands.

ValorValue CondiçãoCondition
zerozero As duas cadeias são iguais.The two strings are equal.
menor que zeroless than zero string1 é menor que string2.string1 is less than string2.
maior que zerogreater than zero string1 é maior que string2.string1 is greater than string2.

Exemplos

O exemplo a seguir compara duas cadeias de caracteres usando as diferentes partes CompareInfo objetos:The following example compares portions of two strings using the different CompareInfo objects:

// The following code example compares two strings using the different CompareInfo instances:
//    a CompareInfo instance associated with the S"Spanish - Spain" culture with international sort,
//    a CompareInfo instance associated with the S"Spanish - Spain" culture with traditional sort, and
//    a CompareInfo instance associated with the InvariantCulture.
using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Defines the strings to compare.
   String^ myStr1 = "calle";
   String^ myStr2 = "calor";
   
   // Uses GetCompareInfo to create the CompareInfo that 
   // uses the S"es-ES" culture with international sort.
   CompareInfo^ myCompIntl = CompareInfo::GetCompareInfo( "es-ES" );
   
   // Uses GetCompareInfo to create the CompareInfo that 
   // uses the S"es-ES" culture with traditional sort.
   CompareInfo^ myCompTrad = CompareInfo::GetCompareInfo( 0x040A );
   
   // Uses the CompareInfo property of the InvariantCulture.
   CompareInfo^ myCompInva = CultureInfo::InvariantCulture->CompareInfo;
   
   // Compares two strings using myCompIntl.
   Console::WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1, myStr2 );
   Console::WriteLine( "   With myCompIntl::Compare: {0}", myCompIntl->Compare( myStr1, myStr2 ) );
   Console::WriteLine( "   With myCompTrad::Compare: {0}", myCompTrad->Compare( myStr1, myStr2 ) );
   Console::WriteLine( "   With myCompInva::Compare: {0}", myCompInva->Compare( myStr1, myStr2 ) );
}

/*
This code produces the following output.

Comparing "calle" and "calor"
   With myCompIntl::Compare: -1
   With myCompTrad::Compare: 1
   With myCompInva::Compare: -1
*/
// The following code example compares two strings using the different CompareInfo instances:
//    a CompareInfo instance associated with the "Spanish - Spain" culture with international sort,
//    a CompareInfo instance associated with the "Spanish - Spain" culture with traditional sort, and
//    a CompareInfo instance associated with the InvariantCulture.

using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "calle";
      String myStr2 = "calor";

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      CompareInfo myCompIntl = CompareInfo.GetCompareInfo( "es-ES" );
      
      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      CompareInfo myCompTrad = CompareInfo.GetCompareInfo( 0x040A );

      // Uses the CompareInfo property of the InvariantCulture.
      CompareInfo myCompInva = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myCompIntl.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1, myStr2 );
      Console.WriteLine( "   With myCompIntl.Compare: {0}", myCompIntl.Compare( myStr1, myStr2 ) );
      Console.WriteLine( "   With myCompTrad.Compare: {0}", myCompTrad.Compare( myStr1, myStr2 ) );
      Console.WriteLine( "   With myCompInva.Compare: {0}", myCompInva.Compare( myStr1, myStr2 ) );

   }

}


/*
This code produces the following output.

Comparing "calle" and "calor"
   With myCompIntl.Compare: -1
   With myCompTrad.Compare: 1
   With myCompInva.Compare: -1

*/
' The following code example compares two strings using the different CompareInfo instances:
'    a CompareInfo instance associated with the "Spanish - Spain" culture with international sort,
'    a CompareInfo instance associated with the "Spanish - Spain" culture with traditional sort, and
'    a CompareInfo instance associated with the InvariantCulture.

Imports System
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "calle"
      Dim myStr2 As [String] = "calor"

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      Dim myCompIntl As CompareInfo = CompareInfo.GetCompareInfo("es-ES")

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      Dim myCompTrad As CompareInfo = CompareInfo.GetCompareInfo(&H40A)

      ' Uses the CompareInfo property of the InvariantCulture.
      Dim myCompInva As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myCompIntl.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1, myStr2)
      Console.WriteLine("   With myCompIntl.Compare: {0}", myCompIntl.Compare(myStr1, myStr2))
      Console.WriteLine("   With myCompTrad.Compare: {0}", myCompTrad.Compare(myStr1, myStr2))
      Console.WriteLine("   With myCompInva.Compare: {0}", myCompInva.Compare(myStr1, myStr2))

   End Sub 'Main 

End Class 'SamplesCompareInfo


'This code produces the following output.
'
'Comparing "calle" and "calor"
'   With myCompIntl.Compare: -1
'   With myCompTrad.Compare: 1
'   With myCompInva.Compare: -1

O exemplo a seguir demonstra a chamada a Compare método.The following example demonstrates calling the Compare method.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;

int main()
{
    array<String^>^ sign = gcnew array<String^> { "<", "=", ">" };

    // The code below demonstrates how strings compare
    // differently for different cultures.
    String^ s1 = "Coté"; 
    String^ s2 = "coté";
    String^ s3 = "côte";

    // Set sort order of strings for French in France.
    CompareInfo^ ci = (gcnew CultureInfo("fr-FR"))->CompareInfo;
    Console::WriteLine(L"The LCID for {0} is {1}.", ci->Name, ci->LCID);

    // Display the result using fr-FR Compare of Coté = coté.
    Console::WriteLine(L"fr-FR Compare: {0} {2} {1}",
        s1, s2, sign[ci->Compare(s1, s2, CompareOptions::IgnoreCase) + 1]);

    // Display the result using fr-FR Compare of coté > côte.
    Console::WriteLine(L"fr-FR Compare: {0} {2} {1}",
        s2, s3, sign[ci->Compare(s2, s3, CompareOptions::None) + 1]);

    // Set sort order of strings for Japanese as spoken in Japan.
    ci = (gcnew CultureInfo("ja-JP"))->CompareInfo;
    Console::WriteLine(L"The LCID for {0} is {1}.", ci->Name, ci->LCID);

    // Display the result using ja-JP Compare of coté < côte.
    Console::WriteLine("ja-JP Compare: {0} {2} {1}",
        s2, s3, sign[ci->Compare(s2, s3) + 1]);
}

// This code produces the following output.
//
// The LCID for fr-FR is 1036.
// fr-FR Compare: Coté = coté
// fr-FR Compare: coté > côte
// The LCID for ja-JP is 1041.
// ja-JP Compare: coté < côte
using System;
using System.Text;
using System.Globalization;

public sealed class App
{
    static void Main(string[] args)
    {
        String[] sign = new String[] { "<", "=", ">" };

        // The code below demonstrates how strings compare 
        // differently for different cultures.
        String s1 = "Coté", s2 = "coté", s3 = "côte";

        // Set sort order of strings for French in France.
        CompareInfo ci = new CultureInfo("fr-FR").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);
      
        // Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s1, s2, sign[ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1]);

        // Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3, CompareOptions.None) + 1]);

        // Set sort order of strings for Japanese as spoken in Japan.
        ci = new CultureInfo("ja-JP").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);

        // Display the result using ja-JP Compare of coté < côte. 
        Console.WriteLine("ja-JP Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3) + 1]);
    }
}

// This code produces the following output.
// 
// The LCID for fr-FR is 1036.
// fr-FR Compare: Coté = coté
// fr-FR Compare: coté > côte
// The LCID for ja-JP is 1041.
// ja-JP Compare: coté < côte
Imports System
Imports System.Text
Imports System.Globalization

NotInheritable Public Class App
    Shared Sub Main(ByVal args() As String) 
        Dim sign() As String = {"<", "=", ">"}
        
        ' The code below demonstrates how strings compare 
        ' differently for different cultures.
        Dim s1 As String = "Coté"
        Dim s2 As String = "coté"
        Dim s3 As String = "côte"
        
        ' Set sort order of strings for French in France.
        Dim ci As CompareInfo = New CultureInfo("fr-FR").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s1, s2, sign((ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1)))
        
        ' Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3, CompareOptions.None) + 1)))
        
        ' Set sort order of strings for Japanese as spoken in Japan.
        ci = New CultureInfo("ja-JP").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using ja-JP Compare of coté < côte. 
        Console.WriteLine("ja-JP Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3) + 1)))
    End Sub 'Main
End Class 'App

' This code produces the following output.
' 
' The LCID for fr-FR is 1036.
' fr-FR Compare: Coté = coté
' fr-FR Compare: coté > côte
' The LCID for ja-JP is 1041.
' ja-JP Compare: coté < côte

Comentários

Por padrão, a comparação é executada usando CompareOptions.None.By default, the comparison is performed by using CompareOptions.None. Se uma decisão de segurança depende de uma comparação de cadeia de caracteres ou uma alteração, você deve usar o InvariantCulture propriedade para garantir que o comportamento é consistente, independentemente das configurações de cultura do sistema operacional.If a security decision depends on a string comparison or a case change, you should use the InvariantCulture property to ensure that the behavior is consistent regardless of the culture settings of the operating system.

Observação

Quando possível, você deve chamar cadeia de caracteres de métodos de comparação que têm um parâmetro de tipo CompareOptions para especificar o tipo de comparação esperado.When possible, you should call string comparison methods that have a parameter of type CompareOptions to specify the kind of comparison expected. Como regra geral, use opções linguísticas (usando a cultura atual) para comparar cadeias de caracteres exibidas na interface do usuário e especifique Ordinal ou OrdinalIgnoreCase para comparações de segurança.As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify Ordinal or OrdinalIgnoreCase for security comparisons.

Notas aos Chamadores

Conjuntos de caracteres incluem caracteres ignoráveis, que são caracteres que não são considerados ao durante a realização de uma comparação linguística ou sensível à cultura.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. O Compare(String, String) método não considera esses caracteres quando ele executa uma comparação sensível à cultura.The Compare(String, String) method does not consider such characters when it performs a culture-sensitive comparison. Por exemplo, uma comparação sensível à cultura de "animal" com "ani-sites perigosos" (usando um hífen ou 00AD U +) indica que duas cadeias de caracteres são equivalentes, como mostra o exemplo a seguir.For instance, a culture-sensitive comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent, as the following example shows.

[!code-vbSystem.Globalization.CompareInfo.Compare#1][!code-vbSystem.Globalization.CompareInfo.Compare#1] Para reconhecer caracteres ignoráveis em uma comparação de cadeia de caracteres, chame o Compare(String, String, CompareOptions) método e fornecer um valor de Ordinal ou OrdinalIgnoreCase para o options parâmetro.To recognize ignorable characters in a string comparison, call the Compare(String, String, CompareOptions) method and supply a value of either Ordinal or OrdinalIgnoreCase for the options parameter.

Compare(String, String, CompareOptions) Compare(String, String, CompareOptions) Compare(String, String, CompareOptions) Compare(String, String, CompareOptions)

Compara duas cadeias de caracteres usando o valor CompareOptions especificado.Compares two strings using the specified CompareOptions value.

public:
 virtual int Compare(System::String ^ string1, System::String ^ string2, System::Globalization::CompareOptions options);
public virtual int Compare (string string1, string string2, System.Globalization.CompareOptions options);
abstract member Compare : string * string * System.Globalization.CompareOptions -> int
override this.Compare : string * string * System.Globalization.CompareOptions -> int
Public Overridable Function Compare (string1 As String, string2 As String, options As CompareOptions) As Integer

Parâmetros

string1
String String String String

A primeira cadeia de caracteres a ser comparada.The first string to compare.

string2
String String String String

A segunda cadeia de caracteres a ser comparada.The second string to compare.

options
CompareOptions CompareOptions CompareOptions CompareOptions

Um valor que define como string1 e string2 devem ser comparados.A value that defines how string1 and string2 should be compared. options é o Ordinal valor de enumeração ou uma combinação bit a bit de um ou mais dos seguintes valores: IgnoreCase, IgnoreSymbols, IgnoreNonSpace, IgnoreWidth, IgnoreKanaType e StringSort.options is either the enumeration value Ordinal, or a bitwise combination of one or more of the following values: IgnoreCase, IgnoreSymbols, IgnoreNonSpace, IgnoreWidth, IgnoreKanaType, and StringSort.

Retornos

Um inteiro com sinal de 32 bits que indica a relação léxica entre os dois termos de comparação.A 32-bit signed integer indicating the lexical relationship between the two comparands.

ValorValue CondiçãoCondition
zerozero As duas cadeias são iguais.The two strings are equal.
menor que zeroless than zero string1 é menor que string2.string1 is less than string2.
maior que zerogreater than zero string1 é maior que string2.string1 is greater than string2.

Exceções

options contém um valor CompareOptions inválido.options contains an invalid CompareOptions value.

Exemplos

O exemplo a seguir compara duas cadeias de caracteres usando diferentes CompareOptions configurações.The following example compares two strings using different CompareOptions settings.

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Defines the strings to compare.
   String^ myStr1 = "My Uncle Bill's clients";
   String^ myStr2 = "My uncle bills clients";
   
   // Creates a CompareInfo which uses the InvariantCulture.
   CompareInfo^ myComp = CultureInfo::InvariantCulture->CompareInfo;
   
   // Compares two strings using myComp.
   Console::WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1, myStr2 );
   Console::WriteLine( "   With no CompareOptions            : {0}", myComp->Compare( myStr1, myStr2 ) );
   Console::WriteLine( "   With None                         : {0}", myComp->Compare( myStr1, myStr2, CompareOptions::None ) );
   Console::WriteLine( "   With Ordinal                      : {0}", myComp->Compare( myStr1, myStr2, CompareOptions::Ordinal ) );
   Console::WriteLine( "   With StringSort                   : {0}", myComp->Compare( myStr1, myStr2, CompareOptions::StringSort ) );
   Console::WriteLine( "   With IgnoreCase                   : {0}", myComp->Compare( myStr1, myStr2, CompareOptions::IgnoreCase ) );
   Console::WriteLine( "   With IgnoreSymbols                : {0}", myComp->Compare( myStr1, myStr2, CompareOptions::IgnoreSymbols ) );
   Console::WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp->Compare( myStr1, myStr2, static_cast<CompareOptions>(CompareOptions::IgnoreCase | CompareOptions::IgnoreSymbols) ) );
}

/*
This code produces the following output.

Comparing "My Uncle Bill's clients" and "My uncle bills clients"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -32
   With StringSort                   : -1
   With IgnoreCase                   : 1
   With IgnoreSymbols                : 1
   With IgnoreCase and IgnoreSymbols : 0
*/
using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "My Uncle Bill's clients";
      String myStr2 = "My uncle bills clients";

      // Creates a CompareInfo that uses the InvariantCulture.
      CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myComp.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1, myStr2 );
      Console.WriteLine( "   With no CompareOptions            : {0}", myComp.Compare( myStr1, myStr2 ) );
      Console.WriteLine( "   With None                         : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.None ) );
      Console.WriteLine( "   With Ordinal                      : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.Ordinal ) );
      Console.WriteLine( "   With StringSort                   : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.StringSort ) );
      Console.WriteLine( "   With IgnoreCase                   : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.IgnoreCase ) );
      Console.WriteLine( "   With IgnoreSymbols                : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.IgnoreSymbols ) );
      Console.WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare( myStr1, myStr2, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols ) );

   }

}


/*
This code produces the following output.

Comparing "My Uncle Bill's clients" and "My uncle bills clients"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -32
   With StringSort                   : -1
   With IgnoreCase                   : 1
   With IgnoreSymbols                : 1
   With IgnoreCase and IgnoreSymbols : 0

*/
Imports System
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "My Uncle Bill's clients"
      Dim myStr2 As [String] = "My uncle bills clients"

      ' Creates a CompareInfo that uses the InvariantCulture.
      Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myComp.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1, myStr2)
      Console.WriteLine("   With no CompareOptions            : {0}", myComp.Compare(myStr1, myStr2))
      Console.WriteLine("   With None                         : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.None))
      Console.WriteLine("   With Ordinal                      : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.Ordinal))
      Console.WriteLine("   With StringSort                   : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.StringSort))
      Console.WriteLine("   With IgnoreCase                   : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase))
      Console.WriteLine("   With IgnoreSymbols                : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreSymbols))
      Console.WriteLine("   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase Or CompareOptions.IgnoreSymbols))

   End Sub 'Main 

End Class 'SamplesCompareInfo


'This code produces the following output.
'
'Comparing "My Uncle Bill's clients" and "My uncle bills clients"
'   With no CompareOptions            : 1
'   With None                         : 1
'   With Ordinal                      : -32
'   With StringSort                   : -1
'   With IgnoreCase                   : 1
'   With IgnoreSymbols                : 1
'   With IgnoreCase and IgnoreSymbols : 0

O exemplo a seguir demonstra a chamada a Compare método.The following example demonstrates calling the Compare method.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;

int main()
{
    array<String^>^ sign = gcnew array<String^> { "<", "=", ">" };

    // The code below demonstrates how strings compare
    // differently for different cultures.
    String^ s1 = "Coté"; 
    String^ s2 = "coté";
    String^ s3 = "côte";

    // Set sort order of strings for French in France.
    CompareInfo^ ci = (gcnew CultureInfo("fr-FR"))->CompareInfo;
    Console::WriteLine(L"The LCID for {0} is {1}.", ci->Name, ci->LCID);

    // Display the result using fr-FR Compare of Coté = coté.
    Console::WriteLine(L"fr-FR Compare: {0} {2} {1}",
        s1, s2, sign[ci->Compare(s1, s2, CompareOptions::IgnoreCase) + 1]);

    // Display the result using fr-FR Compare of coté > côte.
    Console::WriteLine(L"fr-FR Compare: {0} {2} {1}",
        s2, s3, sign[ci->Compare(s2, s3, CompareOptions::None) + 1]);

    // Set sort order of strings for Japanese as spoken in Japan.
    ci = (gcnew CultureInfo("ja-JP"))->CompareInfo;
    Console::WriteLine(L"The LCID for {0} is {1}.", ci->Name, ci->LCID);

    // Display the result using ja-JP Compare of coté < côte.
    Console::WriteLine("ja-JP Compare: {0} {2} {1}",
        s2, s3, sign[ci->Compare(s2, s3) + 1]);
}

// This code produces the following output.
//
// The LCID for fr-FR is 1036.
// fr-FR Compare: Coté = coté
// fr-FR Compare: coté > côte
// The LCID for ja-JP is 1041.
// ja-JP Compare: coté < côte
using System;
using System.Text;
using System.Globalization;

public sealed class App
{
    static void Main(string[] args)
    {
        String[] sign = new String[] { "<", "=", ">" };

        // The code below demonstrates how strings compare 
        // differently for different cultures.
        String s1 = "Coté", s2 = "coté", s3 = "côte";

        // Set sort order of strings for French in France.
        CompareInfo ci = new CultureInfo("fr-FR").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);
      
        // Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s1, s2, sign[ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1]);

        // Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3, CompareOptions.None) + 1]);

        // Set sort order of strings for Japanese as spoken in Japan.
        ci = new CultureInfo("ja-JP").CompareInfo;
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID);

        // Display the result using ja-JP Compare of coté < côte. 
        Console.WriteLine("ja-JP Compare: {0} {2} {1}",
            s2, s3, sign[ci.Compare(s2, s3) + 1]);
    }
}

// This code produces the following output.
// 
// The LCID for fr-FR is 1036.
// fr-FR Compare: Coté = coté
// fr-FR Compare: coté > côte
// The LCID for ja-JP is 1041.
// ja-JP Compare: coté < côte
Imports System
Imports System.Text
Imports System.Globalization

NotInheritable Public Class App
    Shared Sub Main(ByVal args() As String) 
        Dim sign() As String = {"<", "=", ">"}
        
        ' The code below demonstrates how strings compare 
        ' differently for different cultures.
        Dim s1 As String = "Coté"
        Dim s2 As String = "coté"
        Dim s3 As String = "côte"
        
        ' Set sort order of strings for French in France.
        Dim ci As CompareInfo = New CultureInfo("fr-FR").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using fr-FR Compare of Coté = coté.  	
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s1, s2, sign((ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1)))
        
        ' Display the result using fr-FR Compare of coté > côte.
        Console.WriteLine("fr-FR Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3, CompareOptions.None) + 1)))
        
        ' Set sort order of strings for Japanese as spoken in Japan.
        ci = New CultureInfo("ja-JP").CompareInfo
        Console.WriteLine("The LCID for {0} is {1}.", ci.Name, ci.LCID)
        
        ' Display the result using ja-JP Compare of coté < côte. 
        Console.WriteLine("ja-JP Compare: {0} {2} {1}", _
                          s2, s3, sign((ci.Compare(s2, s3) + 1)))
    End Sub 'Main
End Class 'App

' This code produces the following output.
' 
' The LCID for fr-FR is 1036.
' fr-FR Compare: Coté = coté
' fr-FR Compare: coté > côte
' The LCID for ja-JP is 1041.
' ja-JP Compare: coté < côte

Comentários

Se uma decisão de segurança depende de uma comparação de cadeia de caracteres ou uma alteração, você deve usar o InvariantCulture propriedade para garantir que o comportamento é consistente, independentemente das configurações de cultura do sistema operacional.If a security decision depends on a string comparison or a case change, you should use the InvariantCulture property to ensure that the behavior is consistent regardless of the culture settings of the operating system.

Observação

Quando possível, você deve chamar cadeia de caracteres de métodos de comparação que têm um parâmetro de tipo CompareOptions para especificar o tipo de comparação esperado.When possible, you should call string comparison methods that have a parameter of type CompareOptions to specify the kind of comparison expected. Como regra geral, use opções linguísticas (usando a cultura atual) para comparar cadeias de caracteres exibidas na interface do usuário e especifique Ordinal ou OrdinalIgnoreCase para comparações de segurança.As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify Ordinal or OrdinalIgnoreCase for security comparisons.

Notas aos Chamadores

Conjuntos de caracteres incluem caracteres ignoráveis, que são caracteres que não são considerados ao durante a realização de uma comparação linguística ou sensível à cultura.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. O Compare(String, String, CompareOptions) método não considera esses caracteres quando ele executa uma comparação sensível à cultura.The Compare(String, String, CompareOptions) method does not consider such characters when it performs a culture-sensitive comparison. Para reconhecer caracteres ignoráveis em sua comparação, fornecer um valor de Ordinal ou OrdinalIgnoreCase para o options parâmetro.To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

Veja também

Compare(String, Int32, String, Int32) Compare(String, Int32, String, Int32) Compare(String, Int32, String, Int32) Compare(String, Int32, String, Int32)

Compara a seção final de uma cadeia de caracteres com a seção final de outra.Compares the end section of a string with the end section of another string.

public:
 virtual int Compare(System::String ^ string1, int offset1, System::String ^ string2, int offset2);
public virtual int Compare (string string1, int offset1, string string2, int offset2);
abstract member Compare : string * int * string * int -> int
override this.Compare : string * int * string * int -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, string2 As String, offset2 As Integer) As Integer

Parâmetros

string1
String String String String

A primeira cadeia de caracteres a ser comparada.The first string to compare.

offset1
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string1 no qual iniciar a comparação.The zero-based index of the character in string1 at which to start comparing.

string2
String String String String

A segunda cadeia de caracteres a ser comparada.The second string to compare.

offset2
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string2 no qual iniciar a comparação.The zero-based index of the character in string2 at which to start comparing.

Retornos

Um inteiro com sinal de 32 bits que indica a relação léxica entre os dois termos de comparação.A 32-bit signed integer indicating the lexical relationship between the two comparands.

ValorValue CondiçãoCondition
zerozero As duas cadeias são iguais.The two strings are equal.
menor que zeroless than zero A seção especificada de string1 é menor do que a seção especificada de string2.The specified section of string1 is less than the specified section of string2.
maior que zerogreater than zero A seção especificada de string1 é maior do que a seção especificada de string2.The specified section of string1 is greater than the specified section of string2.

Exceções

offset1 ou offset2 é menor que zero.offset1 or offset2 is less than zero.

- ou --or- offset1 é maior ou igual ao número de caracteres em string1.offset1 is greater than or equal to the number of characters in string1.

- ou --or- offset2 é maior ou igual ao número de caracteres em string2.offset2 is greater than or equal to the number of characters in string2.

Exemplos

O exemplo a seguir compara duas cadeias de caracteres usando as diferentes partes CompareInfo objetos:The following example compares portions of two strings using the different CompareInfo objects:

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Defines the strings to compare.
   String^ myStr1 = "calle";
   String^ myStr2 = "calor";
   
   // Uses GetCompareInfo to create the CompareInfo that 
   // uses the S"es-ES" culture with international sort.
   CompareInfo^ myCompIntl = CompareInfo::GetCompareInfo( "es-ES" );
   
   // Uses GetCompareInfo to create the CompareInfo that 
   // uses the S"es-ES" culture with traditional sort.
   CompareInfo^ myCompTrad = CompareInfo::GetCompareInfo( 0x040A );
   
   // Uses the CompareInfo property of the InvariantCulture.
   CompareInfo^ myCompInva = CultureInfo::InvariantCulture->CompareInfo;
   
   // Compares two strings using myCompIntl.
   Console::WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1->Substring( 2 ), myStr2->Substring( 2 ) );
   Console::WriteLine( "   With myCompIntl::Compare: {0}", myCompIntl->Compare( myStr1, 2, myStr2, 2 ) );
   Console::WriteLine( "   With myCompTrad::Compare: {0}", myCompTrad->Compare( myStr1, 2, myStr2, 2 ) );
   Console::WriteLine( "   With myCompInva::Compare: {0}", myCompInva->Compare( myStr1, 2, myStr2, 2 ) );
}

/*
This code produces the following output.

Comparing "lle" and "lor"
   With myCompIntl::Compare: -1
   With myCompTrad::Compare: 1
   With myCompInva::Compare: -1
*/
using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "calle";
      String myStr2 = "calor";

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      CompareInfo myCompIntl = CompareInfo.GetCompareInfo( "es-ES" );
      
      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      CompareInfo myCompTrad = CompareInfo.GetCompareInfo( 0x040A );

      // Uses the CompareInfo property of the InvariantCulture.
      CompareInfo myCompInva = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myCompIntl.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 2 ), myStr2.Substring( 2 ) );
      Console.WriteLine( "   With myCompIntl.Compare: {0}", myCompIntl.Compare( myStr1, 2, myStr2, 2 ) );
      Console.WriteLine( "   With myCompTrad.Compare: {0}", myCompTrad.Compare( myStr1, 2, myStr2, 2 ) );
      Console.WriteLine( "   With myCompInva.Compare: {0}", myCompInva.Compare( myStr1, 2, myStr2, 2 ) );

   }

}


/*
This code produces the following output.

Comparing "lle" and "lor"
   With myCompIntl.Compare: -1
   With myCompTrad.Compare: 1
   With myCompInva.Compare: -1

*/
Imports System
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "calle"
      Dim myStr2 As [String] = "calor"

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      Dim myCompIntl As CompareInfo = CompareInfo.GetCompareInfo("es-ES")

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      Dim myCompTrad As CompareInfo = CompareInfo.GetCompareInfo(&H40A)

      ' Uses the CompareInfo property of the InvariantCulture.
      Dim myCompInva As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myCompIntl.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(2), myStr2.Substring(2))
      Console.WriteLine("   With myCompIntl.Compare: {0}", myCompIntl.Compare(myStr1, 2, myStr2, 2))
      Console.WriteLine("   With myCompTrad.Compare: {0}", myCompTrad.Compare(myStr1, 2, myStr2, 2))
      Console.WriteLine("   With myCompInva.Compare: {0}", myCompInva.Compare(myStr1, 2, myStr2, 2))

   End Sub 'Main 

End Class 'SamplesCompareInfo


'This code produces the following output.
'
'Comparing "lle" and "lor"
'   With myCompIntl.Compare: -1
'   With myCompTrad.Compare: 1
'   With myCompInva.Compare: -1

Comentários

Se uma decisão de segurança depende de uma comparação de cadeia de caracteres ou uma alteração, você deve usar o InvariantCulture propriedade para garantir que o comportamento é consistente, independentemente das configurações de cultura do sistema operacional.If a security decision depends on a string comparison or a case change, you should use the InvariantCulture property to ensure that the behavior is consistent regardless of the culture settings of the operating system.

Observação

Quando possível, você deve chamar cadeia de caracteres de métodos de comparação que têm um parâmetro de tipo CompareOptions para especificar o tipo de comparação esperado.When possible, you should call string comparison methods that have a parameter of type CompareOptions to specify the kind of comparison expected. Como regra geral, use opções linguísticas (usando a cultura atual) para comparar cadeias de caracteres exibidas na interface do usuário e especifique Ordinal ou OrdinalIgnoreCase para comparações de segurança.As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify Ordinal or OrdinalIgnoreCase for security comparisons.

Notas aos Chamadores

Entre conjuntos de caracteres estão caracteres ignoráveis.Character sets include ignorable characters. O Compare(String, Int32, String, Int32) método não considera esses caracteres quando ele executa uma comparação linguística ou sensível à cultura.The Compare(String, Int32, String, Int32) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. Para reconhecer caracteres ignoráveis em sua comparação, chame o Compare(String, Int32, String, Int32, CompareOptions) método e fornecer um valor de Ordinal ou OrdinalIgnoreCase para o options parâmetro.To recognize ignorable characters in your comparison, call the Compare(String, Int32, String, Int32, CompareOptions) method and supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

Compare(String, Int32, String, Int32, CompareOptions) Compare(String, Int32, String, Int32, CompareOptions) Compare(String, Int32, String, Int32, CompareOptions) Compare(String, Int32, String, Int32, CompareOptions)

Compara a seção final de uma cadeia de caracteres com a seção final de outra usando o valor de CompareOptions especificado.Compares the end section of a string with the end section of another string using the specified CompareOptions value.

public:
 virtual int Compare(System::String ^ string1, int offset1, System::String ^ string2, int offset2, System::Globalization::CompareOptions options);
public virtual int Compare (string string1, int offset1, string string2, int offset2, System.Globalization.CompareOptions options);
abstract member Compare : string * int * string * int * System.Globalization.CompareOptions -> int
override this.Compare : string * int * string * int * System.Globalization.CompareOptions -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, string2 As String, offset2 As Integer, options As CompareOptions) As Integer

Parâmetros

string1
String String String String

A primeira cadeia de caracteres a ser comparada.The first string to compare.

offset1
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string1 no qual iniciar a comparação.The zero-based index of the character in string1 at which to start comparing.

string2
String String String String

A segunda cadeia de caracteres a ser comparada.The second string to compare.

offset2
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string2 no qual iniciar a comparação.The zero-based index of the character in string2 at which to start comparing.

options
CompareOptions CompareOptions CompareOptions CompareOptions

Um valor que define como string1 e string2 devem ser comparados.A value that defines how string1 and string2 should be compared. options é o Ordinal valor de enumeração ou uma combinação bit a bit de um ou mais dos seguintes valores: IgnoreCase, IgnoreSymbols, IgnoreNonSpace, IgnoreWidth, IgnoreKanaType e StringSort.options is either the enumeration value Ordinal, or a bitwise combination of one or more of the following values: IgnoreCase, IgnoreSymbols, IgnoreNonSpace, IgnoreWidth, IgnoreKanaType, and StringSort.

Retornos

Um inteiro com sinal de 32 bits que indica a relação léxica entre os dois termos de comparação.A 32-bit signed integer indicating the lexical relationship between the two comparands.

ValorValue CondiçãoCondition
zerozero As duas cadeias são iguais.The two strings are equal.
menor que zeroless than zero A seção especificada de string1 é menor do que a seção especificada de string2.The specified section of string1 is less than the specified section of string2.
maior que zerogreater than zero A seção especificada de string1 é maior do que a seção especificada de string2.The specified section of string1 is greater than the specified section of string2.

Exceções

offset1 ou offset2 é menor que zero.offset1 or offset2 is less than zero.

- ou --or- offset1 é maior ou igual ao número de caracteres em string1.offset1 is greater than or equal to the number of characters in string1.

- ou --or- offset2 é maior ou igual ao número de caracteres em string2.offset2 is greater than or equal to the number of characters in string2.

options contém um valor CompareOptions inválido.options contains an invalid CompareOptions value.

Exemplos

O exemplo a seguir compara duas cadeias de caracteres usando diferentes partes CompareOptions configurações.The following example compares portions of two strings using different CompareOptions settings.

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Defines the strings to compare.
   String^ myStr1 = "My Uncle Bill's clients";
   String^ myStr2 = "My uncle bills clients";
   
   // Creates a CompareInfo that uses the InvariantCulture.
   CompareInfo^ myComp = CultureInfo::InvariantCulture->CompareInfo;
   
   // Compares two strings using myComp.
   Console::WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1->Substring( 10 ), myStr2->Substring( 10 ) );
   Console::WriteLine( "   With no CompareOptions            : {0}", myComp->Compare( myStr1, 10, myStr2, 10 ) );
   Console::WriteLine( "   With None                         : {0}", myComp->Compare( myStr1, 10, myStr2, 10, CompareOptions::None ) );
   Console::WriteLine( "   With Ordinal                      : {0}", myComp->Compare( myStr1, 10, myStr2, 10, CompareOptions::Ordinal ) );
   Console::WriteLine( "   With StringSort                   : {0}", myComp->Compare( myStr1, 10, myStr2, 10, CompareOptions::StringSort ) );
   Console::WriteLine( "   With IgnoreCase                   : {0}", myComp->Compare( myStr1, 10, myStr2, 10, CompareOptions::IgnoreCase ) );
   Console::WriteLine( "   With IgnoreSymbols                : {0}", myComp->Compare( myStr1, 10, myStr2, 10, CompareOptions::IgnoreSymbols ) );
   Console::WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp->Compare( myStr1, 10, myStr2, 10, static_cast<CompareOptions>(CompareOptions::IgnoreCase | CompareOptions::IgnoreSymbols) ) );
}

/*
This code produces the following output.

Comparing "ill's clients" and "ills clients"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -76
   With StringSort                   : -1
   With IgnoreCase                   : 1
   With IgnoreSymbols                : 0
   With IgnoreCase and IgnoreSymbols : 0
*/
using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "My Uncle Bill's clients";
      String myStr2 = "My uncle bills clients";

      // Creates a CompareInfo that uses the InvariantCulture.
      CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myComp.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 10 ), myStr2.Substring( 10 ) );
      Console.WriteLine( "   With no CompareOptions            : {0}", myComp.Compare( myStr1, 10, myStr2, 10 ) );
      Console.WriteLine( "   With None                         : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.None ) );
      Console.WriteLine( "   With Ordinal                      : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.Ordinal ) );
      Console.WriteLine( "   With StringSort                   : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.StringSort ) );
      Console.WriteLine( "   With IgnoreCase                   : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase ) );
      Console.WriteLine( "   With IgnoreSymbols                : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.IgnoreSymbols ) );
      Console.WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare( myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols ) );

   }

}


/*
This code produces the following output.

Comparing "ill's clients" and "ills clients"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -76
   With StringSort                   : -1
   With IgnoreCase                   : 1
   With IgnoreSymbols                : 0
   With IgnoreCase and IgnoreSymbols : 0

*/
Imports System
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "My Uncle Bill's clients"
      Dim myStr2 As [String] = "My uncle bills clients"

      ' Creates a CompareInfo that uses the InvariantCulture.
      Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myComp.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(10), myStr2.Substring(10))
      Console.WriteLine("   With no CompareOptions            : {0}", myComp.Compare(myStr1, 10, myStr2, 10))
      Console.WriteLine("   With None                         : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.None))
      Console.WriteLine("   With Ordinal                      : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.Ordinal))
      Console.WriteLine("   With StringSort                   : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.StringSort))
      Console.WriteLine("   With IgnoreCase                   : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase))
      Console.WriteLine("   With IgnoreSymbols                : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.IgnoreSymbols))
      Console.WriteLine("   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare(myStr1, 10, myStr2, 10, CompareOptions.IgnoreCase Or CompareOptions.IgnoreSymbols))

   End Sub 'Main 

End Class 'SamplesCompareInfo


'This code produces the following output.
'
'Comparing "ill's clients" and "ills clients"
'   With no CompareOptions            : 1
'   With None                         : 1
'   With Ordinal                      : -76
'   With StringSort                   : -1
'   With IgnoreCase                   : 1
'   With IgnoreSymbols                : 0
'   With IgnoreCase and IgnoreSymbols : 0

Comentários

Se uma decisão de segurança depende de uma comparação de cadeia de caracteres ou uma alteração, você deve usar o InvariantCulture propriedade para garantir que o comportamento é consistente, independentemente das configurações de cultura do sistema operacional.If a security decision depends on a string comparison or a case change, you should use the InvariantCulture property to ensure that the behavior is consistent regardless of the culture settings of the operating system.

Observação

Quando possível, você deve chamar cadeia de caracteres de métodos de comparação que têm um parâmetro de tipo CompareOptions para especificar o tipo de comparação esperado.When possible, you should call string comparison methods that have a parameter of type CompareOptions to specify the kind of comparison expected. Como regra geral, use opções linguísticas (usando a cultura atual) para comparar cadeias de caracteres exibidas na interface do usuário e especifique Ordinal ou OrdinalIgnoreCase para comparações de segurança.As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify Ordinal or OrdinalIgnoreCase for security comparisons.

Notas aos Chamadores

Conjuntos de caracteres incluem caracteres ignoráveis, que são caracteres que não são considerados ao durante a realização de uma comparação linguística ou sensível à cultura.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. O Compare(String, Int32, String, Int32, CompareOptions) método não considera esses caracteres ao realizar uma comparação sensível à cultura.The Compare(String, Int32, String, Int32, CompareOptions) method does not consider such characters when performing a culture-sensitive comparison. Para reconhecer caracteres ignoráveis em sua comparação, fornecer um valor de Ordinal ou OrdinalIgnoreCase para o options parâmetro.To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

Veja também

Compare(String, Int32, Int32, String, Int32, Int32) Compare(String, Int32, Int32, String, Int32, Int32) Compare(String, Int32, Int32, String, Int32, Int32) Compare(String, Int32, Int32, String, Int32, Int32)

Compara uma seção de uma cadeia de caracteres com uma seção de outra.Compares a section of one string with a section of another string.

public:
 virtual int Compare(System::String ^ string1, int offset1, int length1, System::String ^ string2, int offset2, int length2);
public virtual int Compare (string string1, int offset1, int length1, string string2, int offset2, int length2);
abstract member Compare : string * int * int * string * int * int -> int
override this.Compare : string * int * int * string * int * int -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, length1 As Integer, string2 As String, offset2 As Integer, length2 As Integer) As Integer

Parâmetros

string1
String String String String

A primeira cadeia de caracteres a ser comparada.The first string to compare.

offset1
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string1 no qual iniciar a comparação.The zero-based index of the character in string1 at which to start comparing.

length1
Int32 Int32 Int32 Int32

O número de caracteres consecutivos em string1 a serem comparados.The number of consecutive characters in string1 to compare.

string2
String String String String

A segunda cadeia de caracteres a ser comparada.The second string to compare.

offset2
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string2 no qual iniciar a comparação.The zero-based index of the character in string2 at which to start comparing.

length2
Int32 Int32 Int32 Int32

O número de caracteres consecutivos em string2 a serem comparados.The number of consecutive characters in string2 to compare.

Retornos

Um inteiro com sinal de 32 bits que indica a relação léxica entre os dois termos de comparação.A 32-bit signed integer indicating the lexical relationship between the two comparands.

ValorValue CondiçãoCondition
zerozero As duas cadeias são iguais.The two strings are equal.
menor que zeroless than zero A seção especificada de string1 é menor do que a seção especificada de string2.The specified section of string1 is less than the specified section of string2.
maior que zerogreater than zero A seção especificada de string1 é maior do que a seção especificada de string2.The specified section of string1 is greater than the specified section of string2.

Exceções

offset1 ou length1 ou offset2 ou length2 é menor que zero.offset1 or length1 or offset2 or length2 is less than zero.

- ou --or- offset1 é maior ou igual ao número de caracteres em string1.offset1 is greater than or equal to the number of characters in string1.

- ou --or- offset2 é maior ou igual ao número de caracteres em string2.offset2 is greater than or equal to the number of characters in string2.

- ou --or- length1 é maior que o número de caracteres de offset1 até o final de string1.length1 is greater than the number of characters from offset1 to the end of string1.

- ou --or- length2 é maior que o número de caracteres de offset2 até o final de string2.length2 is greater than the number of characters from offset2 to the end of string2.

Exemplos

O exemplo a seguir compara duas cadeias de caracteres usando as diferentes partes CompareInfo objetos:The following example compares portions of two strings using the different CompareInfo objects:

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Defines the strings to compare.
   String^ myStr1 = "calle";
   String^ myStr2 = "calor";
   
   // Uses GetCompareInfo to create the CompareInfo that uses the S"es-ES" culture with international sort.
   CompareInfo^ myCompIntl = CompareInfo::GetCompareInfo( "es-ES" );
   
   // Uses GetCompareInfo to create the CompareInfo that uses the S"es-ES" culture with traditional sort.
   CompareInfo^ myCompTrad = CompareInfo::GetCompareInfo( 0x040A );
   
   // Uses the CompareInfo property of the InvariantCulture.
   CompareInfo^ myCompInva = CultureInfo::InvariantCulture->CompareInfo;
   
   // Compares two strings using myCompIntl.
   Console::WriteLine( "Comparing \" {0}\" and \" {1}\"", myStr1->Substring( 2, 2 ), myStr2->Substring( 2, 2 ) );
   Console::WriteLine( "   With myCompIntl->Compare: {0}", myCompIntl->Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
   Console::WriteLine( "   With myCompTrad->Compare: {0}", myCompTrad->Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
   Console::WriteLine( "   With myCompInva->Compare: {0}", myCompInva->Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
}

/*
This code produces the following output.

Comparing S"ll" and S"lo"
With myCompIntl.Compare: -1
With myCompTrad.Compare: 1
With myCompInva.Compare: -1

*/
using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "calle";
      String myStr2 = "calor";

      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      CompareInfo myCompIntl = CompareInfo.GetCompareInfo( "es-ES" );
      
      // Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      CompareInfo myCompTrad = CompareInfo.GetCompareInfo( 0x040A );

      // Uses the CompareInfo property of the InvariantCulture.
      CompareInfo myCompInva = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myCompIntl.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 2, 2 ), myStr2.Substring( 2, 2 ) );
      Console.WriteLine( "   With myCompIntl.Compare: {0}", myCompIntl.Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
      Console.WriteLine( "   With myCompTrad.Compare: {0}", myCompTrad.Compare( myStr1, 2, 2, myStr2, 2, 2 ) );
      Console.WriteLine( "   With myCompInva.Compare: {0}", myCompInva.Compare( myStr1, 2, 2, myStr2, 2, 2 ) );

   }

}


/*
This code produces the following output.

Comparing "ll" and "lo"
   With myCompIntl.Compare: -1
   With myCompTrad.Compare: 1
   With myCompInva.Compare: -1

*/
Imports System
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "calle"
      Dim myStr2 As [String] = "calor"

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with international sort.
      Dim myCompIntl As CompareInfo = CompareInfo.GetCompareInfo("es-ES")

      ' Uses GetCompareInfo to create the CompareInfo that uses the "es-ES" culture with traditional sort.
      Dim myCompTrad As CompareInfo = CompareInfo.GetCompareInfo(&H40A)

      ' Uses the CompareInfo property of the InvariantCulture.
      Dim myCompInva As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myCompIntl.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(2, 2), myStr2.Substring(2, 2))
      Console.WriteLine("   With myCompIntl.Compare: {0}", myCompIntl.Compare(myStr1, 2, 2, myStr2, 2, 2))
      Console.WriteLine("   With myCompTrad.Compare: {0}", myCompTrad.Compare(myStr1, 2, 2, myStr2, 2, 2))
      Console.WriteLine("   With myCompInva.Compare: {0}", myCompInva.Compare(myStr1, 2, 2, myStr2, 2, 2))

   End Sub 'Main 

End Class 'SamplesCompareInfo


'This code produces the following output.
'
'Comparing "ll" and "lo"
'   With myCompIntl.Compare: -1
'   With myCompTrad.Compare: 1
'   With myCompInva.Compare: -1

Comentários

Se uma decisão de segurança depende de uma comparação de cadeia de caracteres ou uma alteração, você deve usar o InvariantCulture propriedade para garantir que o comportamento é consistente, independentemente das configurações de cultura do sistema operacional.If a security decision depends on a string comparison or a case change, you should use the InvariantCulture property to ensure that the behavior is consistent regardless of the culture settings of the operating system.

Observação

Quando possível, você deve usar métodos de comparação de cadeia de caracteres que têm um parâmetro de tipo CompareOptions para especificar o tipo de comparação esperado.When possible, you should use string comparison methods that have a parameter of type CompareOptions to specify the kind of comparison expected. Como regra geral, use opções linguísticas (usando a cultura atual) para comparar cadeias de caracteres exibidas na interface do usuário e especifique Ordinal ou OrdinalIgnoreCase para comparações de segurança.As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify Ordinal or OrdinalIgnoreCase for security comparisons.

Notas aos Chamadores

Entre conjuntos de caracteres estão caracteres ignoráveis.Character sets include ignorable characters. O Compare(String, Int32, Int32, String, Int32, Int32) método não considera esses caracteres quando ele executa uma comparação linguística ou sensível à cultura.The Compare(String, Int32, Int32, String, Int32, Int32) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. Para reconhecer caracteres ignoráveis em sua comparação, chame o Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) método e fornecer um valor de Ordinal ou OrdinalIgnoreCase para o options parâmetro.To recognize ignorable characters in your comparison, call the Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) method and supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions)

Compara uma seção de uma cadeia de caracteres com uma seção de outra usando o valor de CompareOptions especificado.Compares a section of one string with a section of another string using the specified CompareOptions value.

public:
 virtual int Compare(System::String ^ string1, int offset1, int length1, System::String ^ string2, int offset2, int length2, System::Globalization::CompareOptions options);
public virtual int Compare (string string1, int offset1, int length1, string string2, int offset2, int length2, System.Globalization.CompareOptions options);
abstract member Compare : string * int * int * string * int * int * System.Globalization.CompareOptions -> int
override this.Compare : string * int * int * string * int * int * System.Globalization.CompareOptions -> int
Public Overridable Function Compare (string1 As String, offset1 As Integer, length1 As Integer, string2 As String, offset2 As Integer, length2 As Integer, options As CompareOptions) As Integer

Parâmetros

string1
String String String String

A primeira cadeia de caracteres a ser comparada.The first string to compare.

offset1
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string1 no qual iniciar a comparação.The zero-based index of the character in string1 at which to start comparing.

length1
Int32 Int32 Int32 Int32

O número de caracteres consecutivos em string1 a serem comparados.The number of consecutive characters in string1 to compare.

string2
String String String String

A segunda cadeia de caracteres a ser comparada.The second string to compare.

offset2
Int32 Int32 Int32 Int32

O índice de base zero do caractere de string2 no qual iniciar a comparação.The zero-based index of the character in string2 at which to start comparing.

length2
Int32 Int32 Int32 Int32

O número de caracteres consecutivos em string2 a serem comparados.The number of consecutive characters in string2 to compare.

options
CompareOptions CompareOptions CompareOptions CompareOptions

Um valor que define como string1 e string2 devem ser comparados.A value that defines how string1 and string2 should be compared. options é o Ordinal valor de enumeração ou uma combinação bit a bit de um ou mais dos seguintes valores: IgnoreCase, IgnoreSymbols, IgnoreNonSpace, IgnoreWidth, IgnoreKanaType e StringSort.options is either the enumeration value Ordinal, or a bitwise combination of one or more of the following values: IgnoreCase, IgnoreSymbols, IgnoreNonSpace, IgnoreWidth, IgnoreKanaType, and StringSort.

Retornos

Um inteiro com sinal de 32 bits que indica a relação léxica entre os dois termos de comparação.A 32-bit signed integer indicating the lexical relationship between the two comparands.

ValorValue CondiçãoCondition
zerozero As duas cadeias são iguais.The two strings are equal.
menor que zeroless than zero A seção especificada de string1 é menor do que a seção especificada de string2.The specified section of string1 is less than the specified section of string2.
maior que zerogreater than zero A seção especificada de string1 é maior do que a seção especificada de string2.The specified section of string1 is greater than the specified section of string2.

Exceções

offset1 ou length1 ou offset2 ou length2 é menor que zero.offset1 or length1 or offset2 or length2 is less than zero.

- ou --or- offset1 é maior ou igual ao número de caracteres em string1.offset1 is greater than or equal to the number of characters in string1.

- ou --or- offset2 é maior ou igual ao número de caracteres em string2.offset2 is greater than or equal to the number of characters in string2.

- ou --or- length1 é maior que o número de caracteres de offset1 até o final de string1.length1 is greater than the number of characters from offset1 to the end of string1.

- ou --or- length2 é maior que o número de caracteres de offset2 até o final de string2.length2 is greater than the number of characters from offset2 to the end of string2.

options contém um valor CompareOptions inválido.options contains an invalid CompareOptions value.

Exemplos

O exemplo a seguir compara duas cadeias de caracteres usando diferentes partes CompareOptions configurações.The following example compares portions of two strings using different CompareOptions settings.

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Defines the strings to compare.
   String^ myStr1 = "My Uncle Bill's clients";
   String^ myStr2 = "My uncle bills clients";
   
   // Creates a CompareInfo that uses the InvariantCulture.
   CompareInfo^ myComp = CultureInfo::InvariantCulture->CompareInfo;
   
   // Compares two strings using myComp.
   Console::WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1->Substring( 3, 10 ), myStr2->Substring( 3, 10 ) );
   Console::WriteLine( "   With no CompareOptions            : {0}", myComp->Compare( myStr1, 3, 10, myStr2, 3, 10 ) );
   Console::WriteLine( "   With None                         : {0}", myComp->Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions::None ) );
   Console::WriteLine( "   With Ordinal                      : {0}", myComp->Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions::Ordinal ) );
   Console::WriteLine( "   With StringSort                   : {0}", myComp->Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions::StringSort ) );
   Console::WriteLine( "   With IgnoreCase                   : {0}", myComp->Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions::IgnoreCase ) );
   Console::WriteLine( "   With IgnoreSymbols                : {0}", myComp->Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions::IgnoreSymbols ) );
   Console::WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp->Compare( myStr1, 3, 10, myStr2, 3, 10, static_cast<CompareOptions>(CompareOptions::IgnoreCase | CompareOptions::IgnoreSymbols) ) );
}

/*
This code produces the following output.

Comparing "Uncle Bill" and "uncle bill"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -32
   With StringSort                   : 1
   With IgnoreCase                   : 0
   With IgnoreSymbols                : 1
   With IgnoreCase and IgnoreSymbols : 0

*/
using System;
using System.Globalization;

public class SamplesCompareInfo  {

   public static void Main()  {

      // Defines the strings to compare.
      String myStr1 = "My Uncle Bill's clients";
      String myStr2 = "My uncle bills clients";

      // Creates a CompareInfo that uses the InvariantCulture.
      CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;

      // Compares two strings using myComp.
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\"", myStr1.Substring( 3, 10 ), myStr2.Substring( 3, 10 ) );
      Console.WriteLine( "   With no CompareOptions            : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10 ) );
      Console.WriteLine( "   With None                         : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.None ) );
      Console.WriteLine( "   With Ordinal                      : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.Ordinal ) );
      Console.WriteLine( "   With StringSort                   : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.StringSort ) );
      Console.WriteLine( "   With IgnoreCase                   : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase ) );
      Console.WriteLine( "   With IgnoreSymbols                : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreSymbols ) );
      Console.WriteLine( "   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare( myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols ) );

   }

}


/*
This code produces the following output.

Comparing "Uncle Bill" and "uncle bill"
   With no CompareOptions            : 1
   With None                         : 1
   With Ordinal                      : -32
   With StringSort                   : 1
   With IgnoreCase                   : 0
   With IgnoreSymbols                : 1
   With IgnoreCase and IgnoreSymbols : 0

*/
Imports System
Imports System.Globalization

Public Class SamplesCompareInfo

   Public Shared Sub Main()

      ' Defines the strings to compare.
      Dim myStr1 As [String] = "My Uncle Bill's clients"
      Dim myStr2 As [String] = "My uncle bills clients"

      ' Creates a CompareInfo that uses the InvariantCulture.
      Dim myComp As CompareInfo = CultureInfo.InvariantCulture.CompareInfo

      ' Compares two strings using myComp.
      Console.WriteLine("Comparing ""{0}"" and ""{1}""", myStr1.Substring(3, 10), myStr2.Substring(3, 10))
      Console.WriteLine("   With no CompareOptions            : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10))
      Console.WriteLine("   With None                         : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.None))
      Console.WriteLine("   With Ordinal                      : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.Ordinal))
      Console.WriteLine("   With StringSort                   : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.StringSort))
      Console.WriteLine("   With IgnoreCase                   : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase))
      Console.WriteLine("   With IgnoreSymbols                : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreSymbols))
      Console.WriteLine("   With IgnoreCase and IgnoreSymbols : {0}", myComp.Compare(myStr1, 3, 10, myStr2, 3, 10, CompareOptions.IgnoreCase Or CompareOptions.IgnoreSymbols))

   End Sub 'Main 

End Class 'SamplesCompareInfo


'This code produces the following output.
'
'Comparing "Uncle Bill" and "uncle bill"
'   With no CompareOptions            : 1
'   With None                         : 1
'   With Ordinal                      : -32
'   With StringSort                   : 1
'   With IgnoreCase                   : 0
'   With IgnoreSymbols                : 1
'   With IgnoreCase and IgnoreSymbols : 0

Comentários

Se uma decisão de segurança depende de uma comparação de cadeia de caracteres ou uma alteração, você deve usar o InvariantCulture propriedade para garantir que o comportamento é consistente, independentemente das configurações de cultura do sistema operacional.If a security decision depends on a string comparison or a case change, you should use the InvariantCulture property to ensure that the behavior is consistent regardless of the culture settings of the operating system.

Observação

Quando possível, você deve chamar cadeia de caracteres de métodos de comparação que têm um parâmetro de tipo CompareOptions para especificar o tipo de comparação esperado.When possible, you should call string comparison methods that have a parameter of type CompareOptions to specify the kind of comparison expected. Como regra geral, use opções linguísticas (usando a cultura atual) para comparar cadeias de caracteres exibidas na interface do usuário e especifique Ordinal ou OrdinalIgnoreCase para comparações de segurança.As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify Ordinal or OrdinalIgnoreCase for security comparisons.

Notas aos Chamadores

Entre conjuntos de caracteres estão caracteres ignoráveis.Character sets include ignorable characters. O Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) método não considera esses caracteres quando ele executa uma comparação sensível à cultura.The Compare(String, Int32, Int32, String, Int32, Int32, CompareOptions) method does not consider these characters when it performs a culture-sensitive comparison. Para reconhecer caracteres ignoráveis em sua comparação, fornecer um valor de Ordinal ou OrdinalIgnoreCase para o options parâmetro.To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

Veja também

Aplica-se a