Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Método String.Compare (String, String, Boolean)

 

Compara dois objetos String especificados, ignorando ou respeitando as maiúsculas e minúsculas, e retorna um inteiro que indica sua posição relativa na ordem de classificação.

Namespace:   System
Assembly:  mscorlib (em mscorlib.dll)

public static int Compare(
	string strA,
	string strB,
	bool ignoreCase
)

Parâmetros

strA
Type: System.String

A primeira cadeia de caracteres a ser comparada.

strB
Type: System.String

A segunda cadeia de caracteres a ser comparada.

ignoreCase
Type: System.Boolean

true para ignorar maiúsculas durante a comparação; do contrário, false.

Valor Retornado

Type: System.Int32

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

Valor

Condição

Menor do que zero

strA precede strB na ordem de classificação.

Zero

strA ocorre na mesma posição que strB na ordem de classificação.

Maior que zero

strA segue strB na ordem de classificação.

The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

The comparison is performed using word sort rules. For more information about word, string, and ordinal sorts, see T:System.Globalization.CompareOptions.

System_CAPS_warningAviso

When comparing strings, you should call the M:System.String.Compare(System.String,System.String,System.StringComparison) method, which requires that you explicitly specify the type of string comparison that the method uses. For more information, see Best Practices for Using Strings in the .NET Framework.

One or both comparands can be null. By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

The comparison terminates when an inequality is discovered or both strings have been compared. However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. The return value is the result of the last comparison performed.

Unexpected results can occur when comparisons are affected by culture-specific casing rules. For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}

Compare the path name to "file" using an ordinal comparison. The correct code to do this is as follows:

static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}

Observações para os Autores de Chamada:

Character sets include ignorable characters. The M:System.String.Compare(System.String,System.String,System.Boolean) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the netfx40_short or later, a culture-sensitive, case-insensitive comparison of "animal" with "Ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.

using System;

public class Example
{
   public static void Main()
   {
      string s1 = "Ani\u00ADmal";
      string s2 = "animal";

      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, String.Compare(s1, s2, true));
   }
}
// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0

To recognize ignorable characters in a string comparison, call theM:System.String.Compare(System.String,System.String,System.StringComparison)method and supply a value of either F:System.Globalization.CompareOptions.Ordinal or F:System.Globalization.CompareOptions.OrdinalIgnoreCase for the comparisonType parameter.

The following example demonstrates that the M:System.String.Compare(System.String,System.String,System.Boolean) method is equivalent to using M:System.String.ToUpper or M:System.String.ToLower when comparing strings.

using System;

class Example
{
   static void Main()
   {
      // Create upper-case characters from their Unicode code units.
      String stringUpper = "\x0041\x0042\x0043";

      // Create lower-case characters from their Unicode code units.
      String stringLower = "\x0061\x0062\x0063";

      // Display the strings.
      Console.WriteLine("Comparing '{0}' and '{1}':", 
                        stringUpper, stringLower);

      // Compare the uppercased strings; the result is true.
      Console.WriteLine("The Strings are equal when capitalized? {0}",
                        String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0 
                                       ? "true" : "false");

      // The previous method call is equivalent to this Compare method, which ignores case.
      Console.WriteLine("The Strings are equal when case is ignored? {0}",
                        String.Compare(stringUpper, stringLower, true) == 0
                                       ? "true" : "false" );
   }
} 
// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true

Plataforma Universal do Windows
Disponível desde 10
.NET Framework
Disponível desde 1.1
Retornar ao início
Mostrar: