String.Compare Metoda

Definicja

Porównuje dwa określone String obiekty i zwraca liczbę całkowitą, która wskazuje ich względną pozycję w kolejności sortowania.

Przeciążenia

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

Porównuje podciąg dwóch określonych String obiektów przy użyciu określonych opcji porównania i informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą wskazującą relację dwóch podciągów do siebie w kolejności sortowania.

Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)

Porównuje podciąg dwóch określonych String obiektów, ignorując lub honorując ich wielkość liter oraz używając informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

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

Porównuje podciąg dwóch określonych obiektów przy użyciu określonych String reguł i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

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

Porównuje podciąg dwóch określonych String obiektów, ignorując lub honorując ich wielkość liter, i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

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

Porównuje podciąg dwóch określonych String obiektów i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

Compare(String, String)

Porównuje dwa określone String obiekty i zwraca liczbę całkowitą wskazującą ich położenie względne w kolejności sortowania.

Compare(String, String, Boolean, CultureInfo)

Porównuje dwa określone String obiekty, ignorując lub honorując ich przypadek oraz używając informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą wskazującą ich położenie względne w kolejności sortowania.

Compare(String, String, StringComparison)

Porównuje dwa określone String obiekty przy użyciu określonych reguł i zwraca liczbę całkowitą wskazującą ich położenie względne w kolejności sortowania.

Compare(String, String, Boolean)

Porównuje dwa określone String obiekty, ignorując lub honorując ich wielkość liter, i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

Compare(String, String, CultureInfo, CompareOptions)

Porównuje dwa określone String obiekty przy użyciu określonych opcji porównania i informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą wskazującą relację dwóch ciągów ze sobą w kolejności sortowania.

Uwagi

Wszystkie przeciążenia Compare metody zwracają 32-bitową liczbę całkowitą ze znakiem wskazującą relację leksykalną między dwoma comparandami.

Wartość Warunek
Mniej niż zero Pierwszy podciąg poprzedza drugi podciąg w kolejności sortowania.
Zero Podciągy występują w tej samej pozycji w kolejności sortowania lub length ma wartość zero.
Większe od zera Pierwszy podciąg jest zgodny z drugim podciągem w kolejności sortowania.

Ostrzeżenie

Jeśli to możliwe, należy wywołać przeciążenie Compare metody, która zawiera StringComparison parametr. Aby uzyskać więcej informacji, zobacz Najlepsze rozwiązania dotyczące używania ciągów.

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

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje podciąg dwóch określonych String obiektów przy użyciu określonych opcji porównania i informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą wskazującą relację dwóch podciągów do siebie w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, System::Globalization::CultureInfo ^ culture, System::Globalization::CompareOptions options);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);
static member Compare : string * int * string * int * int * System.Globalization.CultureInfo * System.Globalization.CompareOptions -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, culture As CultureInfo, options As CompareOptions) As Integer

Parametry

strA
String

Pierwszy ciąg do użycia w porównaniu.

indexA
Int32

Pozycja początkowa podciągu w obrębie strA.

strB
String

Drugi ciąg do użycia w porównaniu.

indexB
Int32

Pozycja początkowa podciągu w obrębie strB.

length
Int32

Maksymalna liczba znaków w podciągach do porównania.

culture
CultureInfo

Obiekt, który dostarcza informacje porównawcze specyficzne dla kultury. Jeśli culture jest to null, jest używana bieżąca kultura.

options
CompareOptions

Opcje do użycia podczas porównywania (takie jak ignorowanie wielkości liter lub symboli).

Zwraca

Liczba całkowita wskazująca relację leksykalizaną między dwoma podciągami, jak pokazano w poniższej tabeli.

Wartość Warunek
Mniej niż zero Podciąg w strA poprzedniej kolejności sortowania poprzedza podciąg strB .
Zero Podciągy występują w tej samej pozycji w kolejności sortowania lub length są zerowe.
Większe od zera Podciąg w pliku jest strA zgodny z podciągem w strB kolejności sortowania.

Wyjątki

options nie jest wartością CompareOptions .

indexA wartość jest większa niż strA.Length.

-lub-

indexB wartość jest większa niż strB.Length.

-lub-

indexA, indexBlub length jest ujemny.

-lub-

Albo strA lub strB ma nullwartość , a length wartość jest większa niż zero.

Przykłady

W poniższym przykładzie Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) użyto metody do porównania nazwisk dwóch osób. Następnie wyświetla je w kolejności alfabetycznej.

string name1 = "Jack Smith";
string name2 = "John Doe";

// Get position of character after the space character.
int index1 = name1.IndexOf(" ");
index1 = index1 < 0 ? 0 : ++index1;

int index2 = name2.IndexOf(" ");
index2 = index2 < 0 ? 0 : ++index2;

int length = Math.Max(name1.Length, name2.Length);

Console.WriteLine("Sorted alphabetically by last name:");
if (String.Compare(name1, index1, name2, index2, length,
                   new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0)
    Console.WriteLine("{0}\n{1}", name1, name2);
else
    Console.WriteLine("{0}\n{1}", name2, name1);

// The example displays the following output:
//       Sorted alphabetically by last name:
//       John Doe
//       Jack Smith
open System
open System.Globalization

let name1 = "Jack Smith"
let name2 = "John Doe"

// Get position of character after the space character.
let index1 =
    let i = name1.IndexOf " "
    if i < 0 then 0 else i + 1

let index2 = 
    let i = name2.IndexOf " "
    if i < 0 then 0 else i + 1

let length = max name1.Length name2.Length

printfn "Sorted alphabetically by last name:"
if String.Compare(name1, index1, name2, index2, length, CultureInfo "en-US", CompareOptions.IgnoreCase) < 0 then
    printfn $"{name1}\n{name2}"
else
    printfn $"{name2}\n{name1}"

// The example displays the following output:
//       Sorted alphabetically by last name:
//       John Doe
//       Jack Smith
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim name1 As String = "Jack Smith"
      Dim name2 = "John Doe"
      
      ' Get position of space character.
      Dim index1 As Integer = name1.IndexOf(" ")
      index1 = CInt(IIf(index1 < 0, 0, index1 - 1))
      
      Dim index2 As Integer = name2.IndexOf(" ")
      index1 = CInt(IIf(index1 < 0, 0, index1 - 1))
      
      Dim length As Integer = Math.Max(name1.Length, name2.Length)
      
      Console.WriteLIne("Sorted alphabetically by last name:")
      If String.Compare(name1, index1, name2, index2, length, _
                        New CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0 Then
         Console.WriteLine("{0}{1}{2}", name1, vbCrLf, name2)
      Else
         Console.WriteLine("{0}{1}{2}", name2, vbCrLf, name1)
      End If
   End Sub
End Module
' The example displays the following output;
'       Sorted alphabetically by last name:
'       John Doe
'       Jack Smith

Uwagi

Podciągy do porównania w strA pozycji indexA i w strB pozycji indexB. Długość pierwszego podciągu jest długością strA minus indexA. Długość drugiego podciągu jest długością strB minus indexB.

Liczba znaków do porównania jest mniejsza od długości dwóch podciągów i length. Parametry indexA, indexBi length muszą być nienegacyjne.

Porównanie używa parametru culture do uzyskiwania informacji specyficznych dla kultury, takich jak reguły wielkości liter i kolejność alfabetyczna poszczególnych znaków. Na przykład określona kultura może określać, że niektóre kombinacje znaków są traktowane jako pojedynczy znak, że wielkie i małe litery są porównywane w określony sposób lub że kolejność sortowania znaku zależy od znaków poprzedzających lub obserwowanych.

Przestroga

Metoda jest przeznaczona Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) głównie do użycia w operacjach sortowania lub alfabetyzowania. Nie należy jej używać, gdy głównym celem wywołania metody jest określenie, czy dwa podciągy są równoważne (czyli gdy celem wywołania metody jest przetestowanie wartości zwracanej zero). Aby określić, czy dwa ciągi są równoważne, wywołaj metodę Equals .

Jeden lub oba strAstrB elementy mogą mieć wartość null. Według definicji każdy ciąg, w tym String.Empty, porównuje więcej niż odwołanie o wartości null, a dwa odwołania o wartości null porównują się ze sobą.

Porównanie można dodatkowo określić za pomocą parametru options , który składa się z co najmniej jednego elementu członkowskiego wyliczenia System.Globalization.CompareOptions . Jednak ponieważ celem tej metody jest przeprowadzenie porównania ciągów wrażliwych na kulturę, CompareOptions.Ordinal wartości i CompareOptions.OrdinalIgnoreCase nie mają wpływu.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba podciągi. Jeśli jednak dwa ciągi porównują się z końcem jednego ciągu, a drugi ciąg ma pozostałe znaki, ciąg z pozostałymi znakami jest uważany za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) nie uwzględnia tych znaków podczas przeprowadzania porównania językowego lub kulturowego. Aby rozpoznać ignorowane znaki w porównaniu, podaj wartość Ordinal lub OrdinalIgnoreCase dla parametru options .

Zobacz też

Dotyczy

Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje podciąg dwóch określonych String obiektów, ignorując lub honorując ich przypadek i używając informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą, która wskazuje ich względną pozycję w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo? culture);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture);
static member Compare : string * int * string * int * int * bool * System.Globalization.CultureInfo -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean, culture As CultureInfo) As Integer

Parametry

strA
String

Pierwszy ciąg do użycia w porównaniu.

indexA
Int32

Położenie podciągu w obrębie strA.

strB
String

Drugi ciąg do użycia w porównaniu.

indexB
Int32

Położenie podciągu w obrębie strB.

length
Int32

Maksymalna liczba znaków w podciągach do porównania.

ignoreCase
Boolean

true ignorować przypadek podczas porównywania; w przeciwnym razie , false.

culture
CultureInfo

Obiekt, który dostarcza informacje porównawcze specyficzne dla kultury. Jeśli culture jest to null, jest używana bieżąca kultura.

Zwraca

Liczba całkowita wskazująca relację leksykalną między dwoma comparandami.

Wartość Warunek
Mniej niż zero Podciąg w strA kolejności sortowania poprzedza podciąg strB w kolejności sortowania.
Zero Podciągy występują w tej samej pozycji w kolejności sortowania lub length ma wartość zero.
Większe od zera Podciąg w strA obiekcie jest zgodny z podciągem w strB kolejności sortowania.

Wyjątki

indexA wartość jest większa niż strA.Length.

-lub-

indexB wartość jest większa niż strB.Length.

-lub-

indexA, indexBlub length jest ujemny.

-lub-

Albo strA lub strB ma nullwartość , a length wartość jest większa niż zero.

Przykłady

Poniższy przykład porównuje dwa podciągy przy użyciu różnych kultur i ignoruje przypadek podciągów. Wybór kultury wpływa na to, jak jest porównywana litera "I".

// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using namespace System;
using namespace System::Globalization;
int main()
{
   
   //                0123456
   String^ str1 = "MACHINE";
   String^ str2 = "machine";
   String^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
   Console::WriteLine( "Ignore case, Turkish culture:" );
   result = String::Compare( str1, 4, str2, 4, 2, true, gcnew CultureInfo( "tr-TR" ) );
   str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
   Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 4, 2 ), str1 );
   Console::Write( " {0} ", str );
   Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 4, 2 ), str2 );
   Console::WriteLine();
   Console::WriteLine( "Ignore case, invariant culture:" );
   result = String::Compare( str1, 4, str2, 4, 2, true, CultureInfo::InvariantCulture );
   str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
   Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 4, 2 ), str1 );
   Console::Write( " {0} ", str );
   Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 4, 2 ), str2 );
}

/*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.

Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*/
// Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using System;
using System.Globalization;

class Sample5
{
    public static void Main()
    {
        //                 0123456
        String str1 = "MACHINE";
        String str2 = "machine";
        String str;
        int result;

        Console.WriteLine();
        Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
        Console.WriteLine("Ignore case, Turkish culture:");
        result = String.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR"));
        str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
        Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
        Console.Write("{0} ", str);
        Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);

        Console.WriteLine();
        Console.WriteLine("Ignore case, invariant culture:");
        result = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture);
        str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
        Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
        Console.Write("{0} ", str);
        Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
    }
}
/*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.

Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*/
// Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
open System
open System.Globalization

//                 0123456
let str1 = "MACHINE"
let str2 = "machine"

printfn $"\nstr1 = '{str1}', str2 = '{str2}'"
printfn "Ignore case, Turkish culture:"
let result = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo "tr-TR")
let str = if result < 0 then "less than" elif result > 0 then "greater than" else "equal to"
printf $"Substring '{str1.Substring(4, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(4, 2)}' in '{str2}'."

printfn "\nIgnore case, invariant culture:"
let result2 = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture)
let str3 = if result < 0 then "less than" elif result > 0 then "greater than" else "equal to"
printf $"Substring '{str1.Substring(4, 2)}' in '{str1}' is "
printf $"{str3} "
printfn $"substring '{str2.Substring(4, 2)}' in '{str2}'."

(*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.

Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
Imports System.Globalization

Class Sample
   
   Public Shared Sub Main()
      '                       0123456
      Dim str1 As [String] = "MACHINE"
      Dim str2 As [String] = "machine"
      Dim str As [String]
      Dim result As Integer
      
      Console.WriteLine()
      Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
      Console.WriteLine("Ignore case, Turkish culture:")
      result = [String].Compare(str1, 4, str2, 4, 2, True, New CultureInfo("tr-TR"))
      str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
      Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1)
      Console.Write("{0} ", str)
      Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2)
      
      Console.WriteLine()
      Console.WriteLine("Ignore case, invariant culture:")
      result = [String].Compare(str1, 4, str2, 4, 2, True, CultureInfo.InvariantCulture)
      str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
      Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1)
      Console.Write("{0} ", str)
      Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2)
   End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'MACHINE', str2 = 'machine'
'Ignore case, Turkish culture:
'Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.
'
'Ignore case, invariant culture:
'Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
'

Uwagi

Podciągy, które mają być porównywane, zaczynają się od strAindexA, i na .indexBstrB Oba indexA i indexB są oparte na zerach, czyli pierwszy znak w strA i strB znajduje się na pozycji zero, a nie pozycji. Długość pierwszego podciągu jest równa długości strA minus indexA plus jeden. Długość drugiego podciągu jest równa długości strB minus indexB plus jeden.

Liczba znaków do porównania jest mniejsza od długości dwóch podciągów i length. Parametry indexA, indexBi length muszą być nienegacyjne.

Porównanie używa parametru culture do uzyskiwania informacji specyficznych dla kultury, takich jak reguły wielkości liter i kolejność alfabetyczna poszczególnych znaków. Kultura może na przykład określać, że niektóre kombinacje znaków mogą być traktowane jako pojedynczy znak albo że wielkie i małe litery mają być porównywane w określony sposób, albo że porządek sortowania znaków zależy od znaków poprzedzających lub następnych.

Porównanie jest wykonywane przy użyciu reguł sortowania wyrazów. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions.

Jeden lub oba comparands mogą mieć wartość null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba podciągi. Jeśli jednak dwa porównywane ciągi są równe do końca jednego z nich, a drugi ciąg ma jeszcze pozostałe znaki, wówczas ciąg z pozostałymi znakami uznaje się za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Porównaj nazwę ścieżki, aby „uporządkować” według porównania porządkowego. Poprawny kod będzie następujący:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) nie uwzględnia tych znaków podczas przeprowadzania porównania językowego lub kulturowego. Aby rozpoznać w porównaniu możliwe do zignorowania znaki, wywołaj Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) metodę i podaj wartość Ordinal lub OrdinalIgnoreCase dla parametru options .

Zobacz też

Dotyczy

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

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje podciąg dwóch określonych String obiektów przy użyciu określonych reguł i zwraca liczbę całkowitą, która wskazuje ich względną pozycję w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, StringComparison comparisonType);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, StringComparison comparisonType);
static member Compare : string * int * string * int * int * StringComparison -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, comparisonType As StringComparison) As Integer

Parametry

strA
String

Pierwszy ciąg do użycia w porównaniu.

indexA
Int32

Pozycja podciągów w obrębie strA.

strB
String

Drugi ciąg do użycia w porównaniu.

indexB
Int32

Pozycja podciągów w obrębie strB.

length
Int32

Maksymalna liczba znaków w podciągach do porównania.

comparisonType
StringComparison

Jedna z wartości wyliczenia, która określa reguły do użycia w porównaniu.

Zwraca

32-bitowa oznaczona liczba całkowita wskazująca relację leksykalną między dwoma argumentami porównania.

Wartość Warunek
Mniej niż zero Podciąg w strA kolejności sortowania poprzedza podciąg strB w kolejności sortowania.
Zero Podciągy występują w tej samej pozycji w kolejności sortowania lub length parametr ma wartość zero.
Większe od zera Podciąg w strA obiekcie jest zgodny z podciągem w strB kolejności sortowania.

Wyjątki

indexA wartość jest większa niż strA.Length.

-lub-

indexB wartość jest większa niż strB.Length.

-lub-

indexA, indexBlub length jest ujemna.

-lub-

Wartość indexA lub indexB jest nullrówna , a length wartość jest większa niż zero.

comparisonType nie jest wartością StringComparison .

Przykłady

Poniższy przykład porównuje dwa podciągy.

// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main()
{
   
   //                0123456
   String^ str1 = "machine";
   String^ str2 = "device";
   String^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
   result = String::Compare( str1, 2, str2, 0, 2 );
   str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
   Console::Write( "Substring '{0}' in ' {1}' is ", str1->Substring( 2, 2 ), str1 );
   Console::Write( " {0} ", str );
   Console::WriteLine( "substring '{0}' in ' {1}'.", str2->Substring( 0, 2 ), str2 );
}

/*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
String str1 = "machine";
String str2 = "device";
String str;
int result;

Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);

/*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
open System

let str1 = "machine"
let str2 = "device"

printfn "\nstr1 = '{str1}', str2 = '{str2}'"

let result = String.Compare(str1, 2, str2, 0, 2)
let str = 
    if result < 0 then "less than" 
    elif result > 0 then "greater than" 
    else "equal to"

printf $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(0, 2)}' in '{str2}'."

(*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Class Sample
   Public Shared Sub Main()
      '                       0123456
      Dim str1 As [String] = "machine"
      Dim str2 As [String] = "device"
      Dim str As [String]
      Dim result As Integer
      
      Console.WriteLine()
      Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
      result = [String].Compare(str1, 2, str2, 0, 2)
      str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
      Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
      Console.Write("{0} ", str)
      Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2)
   End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'

Uwagi

Podciągy, które mają być porównywane, zaczynają się od strA i indexA w strB .indexB Oba indexA elementy i indexB są oparte na zerach; oznacza to, że pierwszy znak w strA elemecie i strB znajduje się w pozycji zero, a nie na pozycji. Długość pierwszego podciągu jest równa długości strA minus indexA plus jeden. Długość drugiego podciągu jest równa długości strB minus indexB plus jeden.

Liczba znaków do porównania jest mniejsza od długości dwóch podciągów i length. indexAParametry , indexBi length muszą być nienegacyjne.

Parametr comparisonType wskazuje, czy porównanie powinno używać bieżącej lub niezmiennej kultury, honorować lub ignorować wielkość liter współzadzielonego, czy też używać wyrazów (wrażliwych na kulturę) lub porządkowych (niewrażliwych na kulturę) reguł sortowania.

Jeden lub oba comparands mogą mieć wartość null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba podciągi. Jeśli jednak dwa ciągi są porównywane równą końcu jednego ciągu, a drugi ciąg ma pozostałe znaki, ciąg z pozostałymi znakami jest uznawany za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Porównaj nazwę ścieżki, aby „uporządkować” według porównania porządkowego. Poprawny kod będzie następujący:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, Int32, String, Int32, Int32, StringComparison) nie uwzględnia tych znaków podczas przeprowadzania porównania językowego lub wrażliwego na kulturę. Aby rozpoznać znaki możliwe do zignorowania w porównaniu, podaj wartość Ordinal lub OrdinalIgnoreCase dla parametru comparisonType .

Zobacz też

Dotyczy

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

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje podciąg dwóch określonych String obiektów, ignorując lub honorując ich wielkość liter, i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
static member Compare : string * int * string * int * int * bool -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean) As Integer

Parametry

strA
String

Pierwszy ciąg do użycia w porównaniu.

indexA
Int32

Pozycja podciągów w obrębie strA.

strB
String

Drugi ciąg do użycia w porównaniu.

indexB
Int32

Pozycja podciągów w obrębie strB.

length
Int32

Maksymalna liczba znaków w podciągach do porównania.

ignoreCase
Boolean

true ignorować wielkość liter podczas porównywania; w przeciwnym razie , false.

Zwraca

32-bitowa oznaczona liczba całkowita wskazująca relację leksykalną między dwoma argumentami porównania.

Wartość Warunek
Mniej niż zero Podciąg w strA poprzedniej kolejności sortowania poprzedza podciąg strB .
Zero Podciągy występują w tej samej pozycji w kolejności sortowania lub length są zerowe.
Większe od zera Podciąg w pliku jest strA zgodny z podciągem w strB kolejności sortowania.

Wyjątki

indexA wartość jest większa niż strA.Length.

-lub-

indexB wartość jest większa niż strB.Length.

-lub-

indexA, indexBlub length jest ujemna.

-lub-

Wartość indexA lub indexB jest nullrówna , a length wartość jest większa niż zero.

Przykłady

Poniższy przykład wykonuje dwa porównania dwóch podciągów, które różnią się tylko w przypadku. Pierwsze porównanie ignoruje wielkość liter, a drugie porównanie uwzględnia przypadek.

// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean)
using namespace System;
int main()
{
   
   //                0123456
   String^ str1 = "MACHINE";
   String^ str2 = "machine";
   String^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
   Console::WriteLine( "Ignore case:" );
   result = String::Compare( str1, 2, str2, 2, 2, true );
   str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
   Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 2, 2 ), str1 );
   Console::Write( " {0} ", str );
   Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 2, 2 ), str2 );
   Console::WriteLine();
   Console::WriteLine( "Honor case:" );
   result = String::Compare( str1, 2, str2, 2, 2, false );
   str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
   Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 2, 2 ), str1 );
   Console::Write( " {0} ", str );
   Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 2, 2 ), str2 );
}

/*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.

Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*/
String str1 = "MACHINE";
String str2 = "machine";
String str;
int result;

Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);

Console.WriteLine("Ignore case:");
result = String.Compare(str1, 2, str2, 2, 2, true);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
Console.WriteLine();

Console.WriteLine("Honor case:");
result = String.Compare(str1, 2, str2, 2, 2, false);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);

/*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.

Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*/
open System

let str1 = "MACHINE"
let str2 = "machine"

printfn $"\nstr1 = '{str1}', str2 = '{str2}'"

printfn "Ignore case:"
let result = String.Compare(str1, 2, str2, 2, 2, true)
let str = 
    if result < 0 then "less than" 
    elif result > 0 then "greater than"
    else "equal to"

printf $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(2, 2)}' in '{str2}'.\n"

printfn "Honor case:"
let result2 = String.Compare(str1, 2, str2, 2, 2, false)
let str3 = 
    if result < 0 then "less than" 
    elif result > 0 then "greater than" 
    else "equal to"

printfn $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str3} "
printfn $"substring '{str2.Substring(2, 2)}' in '{str2}'."

(*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.

Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean)
Class Sample
   
   Public Shared Sub Main()
      '                       0123456
      Dim str1 As [String] = "MACHINE"
      Dim str2 As [String] = "machine"
      Dim str As [String]
      Dim result As Integer
      
      Console.WriteLine()
      Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
      Console.WriteLine("Ignore case:")
      result = [String].Compare(str1, 2, str2, 2, 2, True)
      str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
      Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
      Console.Write("{0} ", str)
      Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2)
      
      Console.WriteLine()
      Console.WriteLine("Honor case:")
      result = [String].Compare(str1, 2, str2, 2, 2, False)
      str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
      Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
      Console.Write("{0} ", str)
      Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2)
   End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'MACHINE', str2 = 'machine'
'Ignore case:
'Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.
'
'Honor case:
'Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
'

Uwagi

Podciągy do porównania zaczynają się od indexAstrA , i w .indexBstrB Oba indexA elementy i indexB są oparte na zerach; oznacza to, że pierwszy znak w strA elemecie i strB znajduje się w pozycji zero. Długość pierwszego podciągu jest równa długości strA minus indexA plus jeden. Długość drugiego podciągu jest równa długości strB minus indexB plus jeden.

Liczba znaków do porównania jest mniejsza od długości dwóch podciągów i length. indexAParametry , indexBi length muszą być nienegacyjne.

Porównanie używa bieżącej kultury, aby uzyskać informacje specyficzne dla kultury, takie jak reguły obudowy porządkiem alfabetycznym poszczególnych znaków. Kultura może na przykład określać, że niektóre kombinacje znaków mogą być traktowane jako pojedynczy znak albo że wielkie i małe litery mają być porównywane w określony sposób, albo że porządek sortowania znaków zależy od znaków poprzedzających lub następnych.

Porównanie jest wykonywane przy użyciu reguł sortowania wyrazów. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions.

Ostrzeżenie

Podczas porównywania ciągów należy wywołać metodę Compare(String, Int32, String, Int32, Int32, StringComparison) , która wymaga jawnego określenia typu porównania ciągów używanego przez metodę. Aby uzyskać więcej informacji, zobacz Najlepsze rozwiązania dotyczące używania ciągów.

Jeden lub oba comparands mogą mieć wartość null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba podciągi. Jeśli jednak dwa porównywane ciągi są równe do końca jednego z nich, a drugi ciąg ma jeszcze pozostałe znaki, wówczas ciąg z pozostałymi znakami uznaje się za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Nazwa ścieżki musi być porównywana w niezmienny sposób. Prawidłowy kod do wykonania jest następujący.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, Int32, String, Int32, Int32, Boolean) nie uwzględnia tych znaków podczas przeprowadzania porównania językowego lub wrażliwego na kulturę. Aby rozpoznać znaki możliwe do zignorowania w porównaniu, wywołaj metodę Compare(String, Int32, String, Int32, Int32, StringComparison) i podaj wartość Ordinal lub OrdinalIgnoreCase dla parametru comparisonType .

Zobacz też

Dotyczy

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

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje podciąg dwóch określonych String obiektów i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length);
public static int Compare (string strA, int indexA, string strB, int indexB, int length);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length);
static member Compare : string * int * string * int * int -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer) As Integer

Parametry

strA
String

Pierwszy ciąg do użycia w porównaniu.

indexA
Int32

Położenie podciągu w obrębie strA.

strB
String

Drugi ciąg do użycia w porównaniu.

indexB
Int32

Położenie podciągu w obrębie strB.

length
Int32

Maksymalna liczba znaków w podciągach do porównania.

Zwraca

32-bitowa liczba całkowita ze znakiem wskazująca relację leksykalizaną między dwoma comparands.

Wartość Warunek
Mniej niż zero Podciąg w strA poprzedniej kolejności sortowania poprzedza podciąg strB .
Zero Podciągy występują w tej samej pozycji w kolejności sortowania lub length są zerowe.
Większe od zera Podciąg w pliku jest strA zgodny z podciągem w strB kolejności sortowania.

Wyjątki

indexA wartość jest większa niż strA.Length.

-lub-

indexB wartość jest większa niż strB.Length.

-lub-

indexA, indexBlub length jest ujemny.

-lub-

Albo indexA lub indexB ma nullwartość , a length wartość jest większa niż zero.

Przykłady

Poniższy przykład porównuje dwa podciągy.

// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main()
{
   
   //                0123456
   String^ str1 = "machine";
   String^ str2 = "device";
   String^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
   result = String::Compare( str1, 2, str2, 0, 2 );
   str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
   Console::Write( "Substring '{0}' in ' {1}' is ", str1->Substring( 2, 2 ), str1 );
   Console::Write( " {0} ", str );
   Console::WriteLine( "substring '{0}' in ' {1}'.", str2->Substring( 0, 2 ), str2 );
}

/*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
String str1 = "machine";
String str2 = "device";
String str;
int result;

Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);

/*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
open System

let str1 = "machine"
let str2 = "device"

printfn "\nstr1 = '{str1}', str2 = '{str2}'"

let result = String.Compare(str1, 2, str2, 0, 2)
let str = 
    if result < 0 then "less than" 
    elif result > 0 then "greater than" 
    else "equal to"

printf $"Substring '{str1.Substring(2, 2)}' in '{str1}' is "
printf $"{str} "
printfn $"substring '{str2.Substring(0, 2)}' in '{str2}'."

(*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*)
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Class Sample
   Public Shared Sub Main()
      '                       0123456
      Dim str1 As [String] = "machine"
      Dim str2 As [String] = "device"
      Dim str As [String]
      Dim result As Integer
      
      Console.WriteLine()
      Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
      result = [String].Compare(str1, 2, str2, 0, 2)
      str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
      Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
      Console.Write("{0} ", str)
      Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2)
   End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'

Uwagi

Podciągy do porównania zaczynają się strA od i indexA w strB .indexB Oba indexA i indexB są oparte na zerach, czyli pierwszy znak w strA i strB znajduje się na pozycji zero. Długość pierwszego podciągu jest równa długości strA minus indexA plus jeden. Długość drugiego podciągu jest równa długości strB minus indexB plus jeden.

Liczba znaków do porównania jest mniejsza od długości dwóch podciągów i length. Parametry indexA, indexBi length muszą być nienegacyjne.

Porównanie używa bieżącej kultury, aby uzyskać informacje specyficzne dla kultury, takie jak reguły obudowy porządkiem alfabetycznym poszczególnych znaków. Kultura może na przykład określać, że niektóre kombinacje znaków mogą być traktowane jako pojedynczy znak albo że wielkie i małe litery mają być porównywane w określony sposób, albo że porządek sortowania znaków zależy od znaków poprzedzających lub następnych.

Porównanie jest wykonywane przy użyciu reguł sortowania wyrazów. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions.

Ostrzeżenie

Podczas porównywania ciągów należy wywołać metodę Compare(String, Int32, String, Int32, Int32, StringComparison) , która wymaga jawnego określenia typu porównania ciągów, którego używa metoda. Aby uzyskać więcej informacji, zobacz Najlepsze rozwiązania dotyczące używania ciągów.

Jeden lub oba comparands może być null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba podciągi. Jeśli jednak dwa porównywane ciągi są równe do końca jednego z nich, a drugi ciąg ma jeszcze pozostałe znaki, wówczas ciąg z pozostałymi znakami uznaje się za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Porównaj nazwę ścieżki, aby „uporządkować” według porównania porządkowego. Poprawny kod będzie następujący:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, Int32, String, Int32, Int32) nie uwzględnia tych znaków podczas przeprowadzania porównania językowego lub kulturowego. Aby rozpoznać w porównaniu możliwe do zignorowania znaki, wywołaj Compare(String, Int32, String, Int32, Int32, StringComparison) metodę i podaj wartość Ordinal lub OrdinalIgnoreCase dla parametru comparisonType .

Zobacz też

Dotyczy

Compare(String, String)

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje dwa określone String obiekty i zwraca liczbę całkowitą wskazującą ich położenie względne w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, System::String ^ strB);
public static int Compare (string strA, string strB);
public static int Compare (string? strA, string? strB);
static member Compare : string * string -> int
Public Shared Function Compare (strA As String, strB As String) As Integer

Parametry

strA
String

Pierwszy ciąg do porównania.

strB
String

Drugi ciąg do porównania.

Zwraca

32-bitowa oznaczona liczba całkowita wskazująca relację leksykalną między dwoma argumentami porównania.

Wartość Warunek
Mniej niż zerostrAstrB poprzedza kolejność sortowania.
ZerostrA występuje w tej samej pozycji co strB w kolejności sortowania.
Większe od zerastrA następuje strB w kolejności sortowania.

Przykłady

Poniższy przykład wywołuje metodę Compare(String, String) , aby porównać trzy zestawy ciągów.

using namespace System;

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

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

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

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

   // The previous method call is equivalent to this Compare method, which ignores case.
   Console::WriteLine("The Strings are equal when case is ignored? {0}",
                      String::Compare(stringUpper, stringLower, true) == 0
                                      ? "true" : "false");
}
// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true
// Create upper-case characters from their Unicode code units.
String stringUpper = "\x0041\x0042\x0043";

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

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

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

// The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
                String.Compare(stringUpper, stringLower, true) == 0
                               ? "true" : "false" );

// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true
open System

// Create upper-case characters from their Unicode code units.
let stringUpper = "\x0041\x0042\x0043"

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

// Display the strings.
printfn $"Comparing '{stringUpper}' and '{stringLower}':"

// Compare the uppercased strings the result is true.
printfn $"The Strings are equal when capitalized? %b{String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0}"

// The previous method call is equivalent to this Compare method, which ignores case.
printfn $"The Strings are equal when case is ignored? %b{String.Compare(stringUpper, stringLower, true) = 0}"

// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true
Public Module Example
   Public Sub Main()
      ' Create upper-case characters from their Unicode code units.
      Dim stringUpper As String = ChrW(&H41) + ChrW(&H42) + ChrW(&H43)

      ' Create lower-case characters from their Unicode code units.
      Dim stringLower As String = ChrW(&H61) + ChrW(&H62) + ChrW(&H63)

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

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

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

W poniższym przykładzie klasa pokazuje, ReverseStringComparer jak można ocenić dwa ciągi za Compare pomocą metody .

using namespace System;
using namespace System::Text;
using namespace System::Collections;

ref class ReverseStringComparer: public IComparer
{
public:
   virtual int Compare( Object^ x, Object^ y )
   {
      String^ s1 = dynamic_cast<String^>(x);
      String^ s2 = dynamic_cast<String^>(y);

      //negate the return value to get the reverse order
      return  -String::Compare( s1, s2 );
   }

};

void PrintValues( String^ title, IEnumerable^ myList )
{
   Console::Write( "{0,10}: ", title );
   StringBuilder^ sb = gcnew StringBuilder;
   {
      IEnumerator^ en = myList->GetEnumerator();
      String^ s;
      while ( en->MoveNext() )
      {
         s = en->Current->ToString();
         sb->AppendFormat(  "{0}, ", s );
      }
   }
   sb->Remove( sb->Length - 2, 2 );
   Console::WriteLine( sb );
}

void main()
{
   // Creates and initializes a new ArrayList.
   ArrayList^ myAL = gcnew ArrayList;
   myAL->Add( "Eric" );
   myAL->Add( "Mark" );
   myAL->Add( "Lance" );
   myAL->Add( "Rob" );
   myAL->Add( "Kris" );
   myAL->Add( "Brad" );
   myAL->Add( "Kit" );
   myAL->Add( "Bradley" );
   myAL->Add( "Keith" );
   myAL->Add( "Susan" );

   // Displays the properties and values of the ArrayList.
   Console::WriteLine( "Count: {0}", myAL->Count.ToString() );

   PrintValues( "Unsorted", myAL );

   myAL->Sort();
   PrintValues( "Sorted", myAL );

   myAL->Sort( gcnew ReverseStringComparer );
   PrintValues( "Reverse", myAL );

   array<String^>^names = dynamic_cast<array<String^>^>(myAL->ToArray( String::typeid ));
}
using System;
using System.Text;
using System.Collections;

public class SamplesArrayList
{

    public static void Main()
    {
        // Creates and initializes a new ArrayList.
        ArrayList myAL = new ArrayList();
        myAL.Add("Eric");
        myAL.Add("Mark");
        myAL.Add("Lance");
        myAL.Add("Rob");
        myAL.Add("Kris");
        myAL.Add("Brad");
        myAL.Add("Kit");
        myAL.Add("Bradley");
        myAL.Add("Keith");
        myAL.Add("Susan");

        // Displays the properties and values of	the	ArrayList.
        Console.WriteLine("Count: {0}", myAL.Count);

        PrintValues("Unsorted", myAL);
        myAL.Sort();
        PrintValues("Sorted", myAL);
        myAL.Sort(new ReverseStringComparer());
        PrintValues("Reverse", myAL);

        string[] names = (string[])myAL.ToArray(typeof(string));
    }
    public static void PrintValues(string title, IEnumerable myList)
    {
        Console.Write("{0,10}: ", title);
        StringBuilder sb = new StringBuilder();
        foreach (string s in myList)
        {
            sb.AppendFormat("{0}, ", s);
        }
        sb.Remove(sb.Length - 2, 2);
        Console.WriteLine(sb);
    }
}
public class ReverseStringComparer : IComparer
{
    public int Compare(object? x, object? y)
    {
        string? s1 = x as string;
        string? s2 = y as string;
        //negate the return value to get the reverse order
        return -String.Compare(s1, s2);
    }
}
open System
open System.Text
open System.Collections.Generic

type ReverseStringComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            -String.Compare(x, y)

let printValues title (myList: #seq<string>) =
    printf $"{title,10}: "
    let sb = StringBuilder()
    for s in myList do
        sb.Append $"{s}, " |> ignore
    sb.Remove(sb.Length - 2, 2) |> ignore
    printfn $"{sb}"

// Creates and initializes a new ResizeArray.
let myAL = ResizeArray()
myAL.Add "Eric"
myAL.Add "Mark"
myAL.Add "Lance"
myAL.Add "Rob"
myAL.Add "Kris"
myAL.Add "Brad"
myAL.Add "Kit"
myAL.Add "Bradley"
myAL.Add "Keith"
myAL.Add "Susan"

// Displays the properties and values of	the	ArrayList.
printfn $"Count: {myAL.Count}"

printValues "Unsorted" myAL
myAL.Sort()
printValues "Sorted" myAL
myAL.Sort(ReverseStringComparer())
printValues "Reverse" myAL
Imports System.Text
Imports System.Collections



Public Class SamplesArrayList
    
    
    Public Shared Sub Main()
        Dim myAL As New ArrayList()
        ' Creates and initializes a new ArrayList.
        myAL.Add("Eric")
        myAL.Add("Mark")
        myAL.Add("Lance")
        myAL.Add("Rob")
        myAL.Add("Kris")
        myAL.Add("Brad")
        myAL.Add("Kit")
        myAL.Add("Bradley")
        myAL.Add("Keith")
        myAL.Add("Susan")
        
        ' Displays the properties and values of	the	ArrayList.
        Console.WriteLine("Count: {0}", myAL.Count)
        PrintValues("Unsorted", myAL)
        myAL.Sort()
        PrintValues("Sorted", myAL)
        Dim comp as New ReverseStringComparer
        myAL.Sort(comp)
        PrintValues("Reverse", myAL)

        Dim names As String() = CType(myAL.ToArray(GetType(String)), String())
    End Sub
   
   
    
    Public Shared Sub PrintValues(title As String, myList As IEnumerable)
        Console.Write("{0,10}: ", title)
        Dim sb As New StringBuilder()
        Dim s As String
        For Each s In  myList
            sb.AppendFormat("{0}, ", s)
        Next s
        sb.Remove(sb.Length - 2, 2)
        Console.WriteLine(sb)
    End Sub
End Class

Public Class ReverseStringComparer 
  Implements IComparer
    
     Function Compare(x As Object, y As Object) As Integer implements IComparer.Compare
        Dim s1 As String = CStr (x)
        Dim s2 As String = CStr (y)
        
        'negate the return value to get the reverse order
        Return - [String].Compare(s1, s2)
    
    End Function 'Compare
End Class

Uwagi

Porównanie używa bieżącej kultury, aby uzyskać informacje specyficzne dla kultury, takie jak reguły obudowy porządkiem alfabetycznym poszczególnych znaków. Kultura może na przykład określać, że niektóre kombinacje znaków mogą być traktowane jako pojedynczy znak albo że wielkie i małe litery mają być porównywane w określony sposób, albo że porządek sortowania znaków zależy od znaków poprzedzających lub następnych.

Porównanie jest wykonywane przy użyciu reguł sortowania wyrazów. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions.

Ostrzeżenie

Podczas porównywania ciągów należy wywołać metodę Compare(String, String, StringComparison) , która wymaga jawnego określenia typu porównania ciągów, którego używa metoda. Aby uzyskać więcej informacji, zobacz Najlepsze rozwiązania dotyczące używania ciągów.

Jeden lub oba comparands może być null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba ciągi. Jeśli jednak dwa porównywane ciągi są równe do końca jednego z nich, a drugi ciąg ma jeszcze pozostałe znaki, wówczas ciąg z pozostałymi znakami uznaje się za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Porównaj nazwę ścieżki, aby „uporządkować” według porównania porządkowego. Poprawny kod będzie następujący:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, String) nie uwzględnia takich znaków podczas przeprowadzania porównania wrażliwego na kulturę. Jeśli na przykład poniższy kod jest uruchamiany na .NET Framework 4 lub nowszym, wrażliwe na kulturę porównanie "zwierzę" z "ani-mal" (przy użyciu łącznika miękkiego lub U+00AD) wskazuje, że dwa ciągi są równoważne.

string s1 = "ani\u00ADmal";
string s2 = "animal";

Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
                s1, s2, String.Compare(s1, s2));

// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0
open System

let s1 = "ani\u00ADmal"
let s2 = "animal"

printfn $"Comparison of '{s1}' and '{s2}': {String.Compare(s1, s2)}"

// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0
Module Example
   Public Sub Main()
      Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"
      
      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, String.Compare(s1, s2))
  End Sub
End Module
' The example displays the following output:
'       Comparison of 'ani-mal' and 'animal': 0

Aby rozpoznać ignorowane znaki w porównaniu ciągów, wywołaj Compare(String, String, StringComparison) metodę i podaj wartość parametru OrdinalcomparisonType lub OrdinalIgnoreCase .

Zobacz też

Dotyczy

Compare(String, String, Boolean, CultureInfo)

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje dwa określone String obiekty, ignorując lub honorując ich przypadek oraz używając informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą wskazującą ich położenie względne w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, System::String ^ strB, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static int Compare (string? strA, string? strB, bool ignoreCase, System.Globalization.CultureInfo? culture);
public static int Compare (string strA, string strB, bool ignoreCase, System.Globalization.CultureInfo culture);
static member Compare : string * string * bool * System.Globalization.CultureInfo -> int
Public Shared Function Compare (strA As String, strB As String, ignoreCase As Boolean, culture As CultureInfo) As Integer

Parametry

strA
String

Pierwszy ciąg do porównania.

strB
String

Drugi ciąg do porównania.

ignoreCase
Boolean

true ignorować przypadek podczas porównywania; w przeciwnym razie , false.

culture
CultureInfo

Obiekt, który dostarcza informacje porównawcze specyficzne dla kultury. Jeśli culture jest to null, jest używana bieżąca kultura.

Zwraca

32-bitowa oznaczona liczba całkowita wskazująca relację leksykalną między dwoma argumentami porównania.

Wartość Warunek
Mniej niż zerostrAstrB poprzedza kolejność sortowania.
ZerostrA występuje w tej samej pozycji co strB w kolejności sortowania.
Większe od zerastrA następuje strB w kolejności sortowania.

Przykłady

W poniższym przykładzie pokazano, jak kultura może mieć wpływ na porównanie. W języku czeskim - czeskim kultura "ch" jest pojedynczym znakiem, który jest większy niż "d". Jednak w języku angielskim - Stany Zjednoczone kultury "ch" składa się z dwóch znaków, a "c" jest mniej niż "d".

using namespace System;
using namespace System::Globalization;
String^ symbol( int r )
{
   String^ s = "=";
   if ( r < 0 )
      s = "<";
   else
   if ( r > 0 )
      s = ">";


   return s;
}

int main()
{
   String^ str1 = "change";
   String^ str2 = "dollar";
   String^ relation = nullptr;
   relation = symbol( String::Compare( str1, str2, false, gcnew CultureInfo( "en-US" ) ) );
   Console::WriteLine( "For en-US: {0} {1} {2}", str1, relation, str2 );
   relation = symbol( String::Compare( str1, str2, false, gcnew CultureInfo( "cs-CZ" ) ) );
   Console::WriteLine( "For cs-CZ: {0} {1} {2}", str1, relation, str2 );
}

/*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*/
public static void Main()
{
    String str1 = "change";
    String str2 = "dollar";
    String relation;

    relation = symbol(String.Compare(str1, str2, false, new CultureInfo("en-US")));
    Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2);

    relation = symbol(String.Compare(str1, str2, false, new CultureInfo("cs-CZ")));
    Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2);
}

private static String symbol(int r)
{
    String s = "=";
    if (r < 0) s = "<";
    else if (r > 0) s = ">";
    return s;
}

/*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*/
let symbol r =
    if r < 0 then "<"
    elif r > 0 then ">"
    else "="

let str1 = "change"
let str2 = "dollar"

let relation1 = 
    String.Compare(str1, str2, false, CultureInfo "en-US")
    |> symbol
printfn $"For en-US: {str1} {relation1} {str2}"

let relation2 = 
    String.Compare(str1, str2, false, CultureInfo "cs-CZ")
    |> symbol
printfn $"For cs-CZ: {str1} {relation2} {str2}"

(*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*)
Imports System.Globalization
 _

Class Sample
   Public Shared Sub Main()
      Dim str1 As [String] = "change"
      Dim str2 As [String] = "dollar"
      Dim relation As [String] = Nothing
      
      relation = symbol([String].Compare(str1, str2, False, New CultureInfo("en-US")))
      Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2)
      
      relation = symbol([String].Compare(str1, str2, False, New CultureInfo("cs-CZ")))
      Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2)
   End Sub
   
   Private Shared Function symbol(r As Integer) As [String]
      Dim s As [String] = "="
      If r < 0 Then
         s = "<"
      Else
         If r > 0 Then
            s = ">"
         End If
      End If
      Return s
   End Function 'symbol
End Class
'
'This example produces the following results.
'For en-US: change < dollar
'For cs-CZ: change > dollar
'

Uwagi

Porównanie używa parametru culture do uzyskiwania informacji specyficznych dla kultury, takich jak reguły wielkości liter i kolejność alfabetyczna poszczególnych znaków. Kultura może na przykład określać, że niektóre kombinacje znaków mogą być traktowane jako pojedynczy znak albo że wielkie i małe litery mają być porównywane w określony sposób, albo że porządek sortowania znaków zależy od znaków poprzedzających lub następnych.

Porównanie jest wykonywane przy użyciu reguł sortowania wyrazów. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions.

Jeden lub oba comparands może być null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba ciągi. Jeśli jednak dwa porównywane ciągi są równe do końca jednego z nich, a drugi ciąg ma jeszcze pozostałe znaki, wówczas ciąg z pozostałymi znakami uznaje się za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Porównaj nazwę ścieżki, aby „uporządkować” według porównania porządkowego. Poprawny kod będzie następujący:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, String, Boolean, CultureInfo) nie uwzględnia takich znaków podczas przeprowadzania porównania wrażliwego na kulturę. Jeśli na przykład poniższy kod jest uruchamiany na .NET Framework 4 lub nowszym, niewrażliwe na wielkość liter porównanie "zwierzę" z "Ani-mal" (przy użyciu łącznika miękkiego lub U+00AD) przy użyciu niezmiennej kultury wskazuje, że dwa ciągi są równoważne.

  string s1 = "Ani\u00ADmal";
  string s2 = "animal";

  Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                  s1, s2, String.Compare(s1, s2, true,
                  CultureInfo.InvariantCulture));

  // The example displays the following output:
  //       Comparison of 'Ani-mal' and 'animal': 0
open System
open System.Globalization

let s1 = "Ani\u00ADmal"
let s2 = "animal"

printfn $"Comparison of '{s1}' and '{s2}': {String.Compare(s1, s2, true, CultureInfo.InvariantCulture)}"

// The example displays the following output:
//       Comparison of 'Ani-mal' and 'animal': 0
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim s1 As String = "Ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"
      
      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, String.Compare(s1, s2, True,
                        CultureInfo.InvariantCulture))
  End Sub
End Module
' The example displays the following output:
'       Comparison of 'ani-mal' and 'animal': 0

Aby rozpoznać ignorowane znaki w porównaniu ciągów, wywołaj Compare(String, String, CultureInfo, CompareOptions) metodę i podaj wartość parametru Ordinaloptions lub OrdinalIgnoreCase .

Zobacz też

Dotyczy

Compare(String, String, StringComparison)

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje dwa określone String obiekty przy użyciu określonych reguł i zwraca liczbę całkowitą wskazującą ich położenie względne w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, System::String ^ strB, StringComparison comparisonType);
public static int Compare (string strA, string strB, StringComparison comparisonType);
public static int Compare (string? strA, string? strB, StringComparison comparisonType);
static member Compare : string * string * StringComparison -> int
Public Shared Function Compare (strA As String, strB As String, comparisonType As StringComparison) As Integer

Parametry

strA
String

Pierwszy ciąg do porównania.

strB
String

Drugi ciąg do porównania.

comparisonType
StringComparison

Jedna z wartości wyliczenia, która określa reguły do użycia w porównaniu.

Zwraca

32-bitowa oznaczona liczba całkowita wskazująca relację leksykalną między dwoma argumentami porównania.

Wartość Warunek
Mniej niż zerostrAstrB poprzedza kolejność sortowania.
ZerostrA znajduje się w tej samej pozycji co strB w kolejności sortowania.
Większe od zerastrA następuje strB w kolejności sortowania.

Wyjątki

comparisonType nie jest wartością StringComparison .

StringComparison nie jest obsługiwane.

Przykłady

Poniższy przykład porównuje trzy wersje litery "I". Wyniki mają wpływ na wybór kultury, niezależnie od tego, czy wielkość liter jest ignorowana, i czy jest wykonywane porównanie porządkowe.

// This example demonstrates the
// System.String.Compare(String, String, StringComparison) method.

using namespace System;
using namespace System::Threading;

void Test(int testStringIndex, int searchStringIndex, 
          StringComparison comparison, array<String^>^ testI, 
          array<String^>^ testNames)
{
    String^ resultFormat = "{0} is {1} {2}";
    String^ resultString = "equal to";
    int comparisonValue = 0;

    comparisonValue = String::Compare(testI[testStringIndex],
        testI[searchStringIndex], comparison);
    if (comparisonValue < 0)
    {
        resultString = "less than";
    }
    else if (comparisonValue > 0)
    {
        resultString = "greater than";
    }
    Console::WriteLine(resultFormat, testNames[testStringIndex], resultString,
        testNames[searchStringIndex]);
}

int main()
{
    String^ introMessage =
        "Compare three versions of the letter I using different " +
        "values of StringComparison.";

    // Define an array of strings where each element contains a version of
    // the letter I. (An array of strings is used so you can easily modify
    // this code example to test additional or different combinations of
    // strings.)

    array<String^>^ letterVariation = gcnew array<String^>(3);
    // LATIN SMALL LETTER I (U+0069)
    letterVariation[0] = "i";
    // LATIN SMALL LETTER DOTLESS I (U+0131)
    letterVariation[1] = L"\u0131";
    // LATIN CAPITAL LETTER I (U+0049)
    letterVariation[2] = "I";

    array<String^>^ unicodeNames = {
        "LATIN SMALL LETTER I (U+0069)",
        "LATIN SMALL LETTER DOTLESS I (U+0131)",
        "LATIN CAPITAL LETTER I (U+0049)"};

    array<StringComparison>^ comparisonValues = {
        StringComparison::CurrentCulture,
        StringComparison::CurrentCultureIgnoreCase,
        StringComparison::InvariantCulture,
        StringComparison::InvariantCultureIgnoreCase,
        StringComparison::Ordinal,
        StringComparison::OrdinalIgnoreCase};

    Console::Clear();
    Console::WriteLine(introMessage);

    // Display the current culture because the culture-specific comparisons
    // can produce different results with different cultures.
    Console::WriteLine("The current culture is {0}.{1}",
        Thread::CurrentThread->CurrentCulture->Name, Environment::NewLine);

    // Determine the relative sort order of three versions of the letter I.
    for each (StringComparison stringCmp in comparisonValues)
    {
        Console::WriteLine("StringComparison.{0}:", stringCmp);

        // LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I
        // (U+0131)
        Test(0, 1, stringCmp, letterVariation, unicodeNames);

        // LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
        Test(0, 2, stringCmp, letterVariation, unicodeNames);

        // LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I
        // (U+0049)
        Test(1, 2, stringCmp, letterVariation, unicodeNames);

        Console::WriteLine();
    }
}

/*
This code example produces the following results:

Compare three versions of the letter I using different values of 
StringComparison.
The current culture is en-US.

StringComparison.CurrentCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER 
  DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN 
  CAPITAL LETTER I (U+0049)

StringComparison.CurrentCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER 
  DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN 
  CAPITAL LETTER I (U+0049)

StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER 
  DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN 
  CAPITAL LETTER I (U+0049)

StringComparison.InvariantCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER 
  DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN 
  CAPITAL LETTER I (U+0049)

StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER 
  DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN 
  CAPITAL LETTER I (U+0049)

StringComparison.OrdinalIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER 
  DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN 
  CAPITAL LETTER I (U+0049)

*/
// This example demonstrates the 
// System.String.Compare(String, String, StringComparison) method.

using System;
using System.Threading;

class Sample 
{
    public static void Main() 
    {
        string intro = "Compare three versions of the letter I using different " + 
                       "values of StringComparison.";

        // Define an array of strings where each element contains a version of the 
        // letter I. (An array of strings is used so you can easily modify this 
        // code example to test additional or different combinations of strings.)  

        string[] threeIs = new string[3];
        // LATIN SMALL LETTER I (U+0069)
        threeIs[0] = "\u0069";
        // LATIN SMALL LETTER DOTLESS I (U+0131)
        threeIs[1] = "\u0131";
        // LATIN CAPITAL LETTER I (U+0049)
        threeIs[2] = "\u0049";

        string[] unicodeNames = 
        {
            "LATIN SMALL LETTER I (U+0069)", 
            "LATIN SMALL LETTER DOTLESS I (U+0131)", 
            "LATIN CAPITAL LETTER I (U+0049)"
        };

        StringComparison[] scValues =
        {
            StringComparison.CurrentCulture,
            StringComparison.CurrentCultureIgnoreCase,
            StringComparison.InvariantCulture,
            StringComparison.InvariantCultureIgnoreCase,
            StringComparison.Ordinal,
            StringComparison.OrdinalIgnoreCase
        };

        Console.Clear();
        Console.WriteLine(intro);

        // Display the current culture because the culture-specific comparisons
        // can produce different results with different cultures.
        Console.WriteLine(
            "The current culture is {0}.\n", Thread.CurrentThread.CurrentCulture.Name);

        // Determine the relative sort order of three versions of the letter I. 
        foreach (StringComparison sc in scValues)
        {
            Console.WriteLine("StringComparison.{0}:", sc);

            // LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
            Test(0, 1, sc, threeIs, unicodeNames);

            // LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
            Test(0, 2, sc, threeIs, unicodeNames);

            // LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
            Test(1, 2, sc, threeIs, unicodeNames);

            Console.WriteLine();
        }
    }

    protected static void Test(
        int x, int y, StringComparison comparison, string[] testI, string[] testNames)
    {
        string resultFmt = "{0} is {1} {2}";
        string result = "equal to";
        int cmpValue = 0;

        cmpValue = String.Compare(testI[x], testI[y], comparison);
        if (cmpValue < 0)
            result = "less than";
        else if (cmpValue > 0)
            result = "greater than";
        Console.WriteLine(resultFmt, testNames[x], result, testNames[y]);
    }
}

/*
This code example produces the following results:

Compare three versions of the letter I using different values of StringComparison.
The current culture is en-US.

StringComparison.CurrentCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.CurrentCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.InvariantCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.OrdinalIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

*/
// This example demonstrates the 
// System.String.Compare(String, String, StringComparison) method.

open System
open System.Threading

let test x y (comparison: StringComparison) (testI: string[]) (testNames: string[]) =
    let cmpValue = String.Compare(testI[x], testI[y], comparison)
    let result =
        if cmpValue < 0 then
            "less than"
        elif cmpValue > 0 then
            "greater than"
        else
            "equal to"
    printfn $"{testNames[x]} is {result} {testNames[y]}"

let intro = "Compare three versions of the letter I using different values of StringComparison."

// Define an array of strings where each element contains a version of the 
// letter I. (An array of strings is used so you can easily modify this 
// code example to test additional or different combinations of strings.)  

let threeIs = 
  [|// LATIN SMALL LETTER I (U+0069)
    "\u0069"
    // LATIN SMALL LETTER DOTLESS I (U+0131)
    "\u0131"
    // LATIN CAPITAL LETTER I (U+0049)
    "\u0049" |]

let unicodeNames =
    [| "LATIN SMALL LETTER I (U+0069)"
       "LATIN SMALL LETTER DOTLESS I (U+0131)"
       "LATIN CAPITAL LETTER I (U+0049)" |]

let scValues =
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase |]

Console.Clear()
printfn $"{intro}"

// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
printfn $"The current culture is {Thread.CurrentThread.CurrentCulture.Name}.\n"

// Determine the relative sort order of three versions of the letter I. 
for sc in scValues do
    printfn $"StringComparison.{sc}:"

    // LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
    test 0 1 sc threeIs unicodeNames

    // LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
    test 0 2 sc threeIs unicodeNames

    // LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
    test 1 2 sc threeIs unicodeNames

    printfn ""

(*
This code example produces the following results:

Compare three versions of the letter I using different values of StringComparison.
The current culture is en-US.

StringComparison.CurrentCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.CurrentCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.InvariantCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.OrdinalIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
*)
' This example demonstrates the 
' System.String.Compare(String, String, StringComparison) method.

Imports System.Threading

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Compare three versions of the letter I using different " & _
                              "values of StringComparison."
        
        ' Define an array of strings where each element contains a version of the 
        ' letter I. (An array of strings is used so you can easily modify this 
        ' code example to test additional or different combinations of strings.)  
        Dim threeIs(2) As String
        ' LATIN SMALL LETTER I (U+0069)
        threeIs(0) = "i"
        ' LATIN SMALL LETTER DOTLESS I (U+0131)
        threeIs(1) = "ı"
        ' LATIN CAPITAL LETTER I (U+0049)
        threeIs(2) = "I"
        
        Dim unicodeNames As String() =  { _
                            "LATIN SMALL LETTER I (U+0069)", _
                            "LATIN SMALL LETTER DOTLESS I (U+0131)", _
                            "LATIN CAPITAL LETTER I (U+0049)" }
        
        Dim scValues As StringComparison() =  { _
                            StringComparison.CurrentCulture, _
                            StringComparison.CurrentCultureIgnoreCase, _
                            StringComparison.InvariantCulture, _
                            StringComparison.InvariantCultureIgnoreCase, _
                            StringComparison.Ordinal, _
                            StringComparison.OrdinalIgnoreCase }
        '
        Console.Clear()
        Console.WriteLine(intro)
        
        ' Display the current culture because the culture-specific comparisons
        ' can produce different results with different cultures.
        Console.WriteLine("The current culture is {0}." & vbCrLf, _
                           Thread.CurrentThread.CurrentCulture.Name)
        
        ' Determine the relative sort order of three versions of the letter I. 
        Dim sc As StringComparison
        For Each sc In  scValues
            Console.WriteLine("StringComparison.{0}:", sc)
            
            ' LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
            Test(0, 1, sc, threeIs, unicodeNames)
            
            ' LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
            Test(0, 2, sc, threeIs, unicodeNames)
            
            ' LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
            Test(1, 2, sc, threeIs, unicodeNames)
            
            Console.WriteLine()
        Next sc
    
    End Sub
    
    Protected Shared Sub Test(ByVal x As Integer, ByVal y As Integer, _
                              ByVal comparison As StringComparison, _
                              ByVal testI() As String, ByVal testNames() As String) 
        Dim resultFmt As String = "{0} is {1} {2}"
        Dim result As String = "equal to"
        Dim cmpValue As Integer = 0
        '
        cmpValue = String.Compare(testI(x), testI(y), comparison)
        If cmpValue < 0 Then
            result = "less than"
        ElseIf cmpValue > 0 Then
            result = "greater than"
        End If
        Console.WriteLine(resultFmt, testNames(x), result, testNames(y))
    
    End Sub
End Class

'
'This code example produces the following results:
'
'Compare three versions of the letter I using different values of StringComparison.
'The current culture is en-US.
'
'StringComparison.CurrentCulture:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.CurrentCultureIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.InvariantCulture:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.InvariantCultureIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.Ordinal:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.OrdinalIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'

Uwagi

Parametr comparisonType wskazuje, czy porównanie powinno używać bieżącej lub niezmiennej kultury, honorować lub ignorować przypadek comparands, czy też używać wyrazu (wrażliwego na kulturę) lub porządkowego (niewrażliwego na kulturę) reguł sortowania.

Jeden lub oba comparands może być null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba ciągi. Jeśli jednak dwa ciągi porównują się z końcem jednego ciągu, a drugi ciąg ma pozostałe znaki, ciąg z pozostałymi znakami jest uważany za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Porównaj nazwę ścieżki, aby „uporządkować” według porównania porządkowego. Poprawny kod będzie następujący:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, String, StringComparison) nie uwzględnia takich znaków podczas przeprowadzania porównania wrażliwego na kulturę. Aby rozpoznać ignorowane znaki w porównaniu, podaj wartość Ordinal lub OrdinalIgnoreCase dla parametru comparisonType .

Zobacz też

Dotyczy

Compare(String, String, Boolean)

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje dwa określone String obiekty, ignorując lub honorując ich wielkość liter, i zwraca liczbę całkowitą wskazującą ich względną pozycję w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, System::String ^ strB, bool ignoreCase);
public static int Compare (string strA, string strB, bool ignoreCase);
public static int Compare (string? strA, string? strB, bool ignoreCase);
static member Compare : string * string * bool -> int
Public Shared Function Compare (strA As String, strB As String, ignoreCase As Boolean) As Integer

Parametry

strA
String

Pierwszy ciąg do porównania.

strB
String

Drugi ciąg do porównania.

ignoreCase
Boolean

true ignorować przypadek podczas porównywania; w przeciwnym razie , false.

Zwraca

32-bitowa oznaczona liczba całkowita wskazująca relację leksykalną między dwoma argumentami porównania.

Wartość Warunek
Mniej niż zerostrAstrB poprzedza kolejność sortowania.
ZerostrA występuje w tej samej pozycji co strB w kolejności sortowania.
Większe od zerastrA następuje strB w kolejności sortowania.

Przykłady

W poniższym przykładzie pokazano, że Compare(String, String, Boolean) metoda jest równoważna użyciu ToUpper lub ToLower podczas porównywania ciągów.

using namespace System;

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

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

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

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

   // The previous method call is equivalent to this Compare method, which ignores case.
   Console::WriteLine("The Strings are equal when case is ignored? {0}",
                      String::Compare(stringUpper, stringLower, true) == 0
                                      ? "true" : "false");
}
// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true
// Create upper-case characters from their Unicode code units.
String stringUpper = "\x0041\x0042\x0043";

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

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

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

// The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
                String.Compare(stringUpper, stringLower, true) == 0
                               ? "true" : "false" );

// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true
open System

// Create upper-case characters from their Unicode code units.
let stringUpper = "\x0041\x0042\x0043"

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

// Display the strings.
printfn $"Comparing '{stringUpper}' and '{stringLower}':"

// Compare the uppercased strings the result is true.
printfn $"The Strings are equal when capitalized? %b{String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0}"

// The previous method call is equivalent to this Compare method, which ignores case.
printfn $"The Strings are equal when case is ignored? %b{String.Compare(stringUpper, stringLower, true) = 0}"

// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true
Public Module Example
   Public Sub Main()
      ' Create upper-case characters from their Unicode code units.
      Dim stringUpper As String = ChrW(&H41) + ChrW(&H42) + ChrW(&H43)

      ' Create lower-case characters from their Unicode code units.
      Dim stringLower As String = ChrW(&H61) + ChrW(&H62) + ChrW(&H63)

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

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

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

Uwagi

Porównanie używa bieżącej kultury, aby uzyskać informacje specyficzne dla kultury, takie jak reguły obudowy porządkiem alfabetycznym poszczególnych znaków. Kultura może na przykład określać, że niektóre kombinacje znaków mogą być traktowane jako pojedynczy znak albo że wielkie i małe litery mają być porównywane w określony sposób, albo że porządek sortowania znaków zależy od znaków poprzedzających lub następnych.

Porównanie jest wykonywane przy użyciu reguł sortowania wyrazów. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions.

Ostrzeżenie

Podczas porównywania ciągów należy wywołać metodę Compare(String, String, StringComparison) , która wymaga jawnego określenia typu porównania ciągów, którego używa metoda. Aby uzyskać więcej informacji, zobacz Najlepsze rozwiązania dotyczące używania ciągów.

Jeden lub oba comparands może być null. Według definicji dowolny ciąg, w tym ciąg pusty (""), porównuje odwołania o wartości większej niż zerowa; wskazuje też, że dwa odwołania zerowe są sobie równe.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba ciągi. Jeśli jednak dwa porównywane ciągi są równe do końca jednego z nich, a drugi ciąg ma jeszcze pozostałe znaki, wówczas ciąg z pozostałymi znakami uznaje się za większy. Zwracana wartość jest wynikiem ostatniego wykonanego porównania.

Gdy na porównania wpływają reguły uwzględniające ustawienia kulturowe, mogą wystąpić nieoczekiwane rezultaty. Na przykład w języku tureckim poniższy przykład daje błędne wyniki, ponieważ system plików w tym języku nie używa reguł wielkich liter dla litery „i” w wyrazie „plik”.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, true) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Porównaj nazwę ścieżki, aby „uporządkować” według porównania porządkowego. Poprawny kod będzie następujący:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
let isFileURI path =
    String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0
Shared Function IsFileURI(ByVal path As String) As Boolean
    If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Uwagi dotyczące wywoływania

Zestawy znaków obejmują znaki do pominięcia. Metoda Compare(String, String, Boolean) nie uwzględnia takich znaków podczas przeprowadzania porównania wrażliwego na kulturę. Jeśli na przykład poniższy kod jest uruchamiany na .NET Framework 4 lub nowszym, wrażliwe na kulturę, bez uwzględniania wielkości liter porównanie "zwierzę" z "Ani-mal" (przy użyciu łącznika miękkiego lub U+00AD) wskazuje, że dwa ciągi są równoważne.

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

let s1 = "Ani\u00ADmal"
let s2 = "animal"

printfn $"Comparison of '{s1}' and '{s2}': {String.Compare(s1, s2, true)}"

// The example displays the following output:
//       Comparison of 'Ani-mal' and 'animal': 0
Module Example
   Public Sub Main()
      Dim s1 As String = "Ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"
      
      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, String.Compare(s1, s2, True))
  End Sub
End Module
' The example displays the following output:
'       Comparison of 'ani-mal' and 'animal': 0

Aby rozpoznać ignorowane znaki w porównaniu ciągów, wywołaj Compare(String, String, StringComparison) metodę i podaj wartość parametru OrdinalcomparisonType lub OrdinalIgnoreCase .

Zobacz też

Dotyczy

Compare(String, String, CultureInfo, CompareOptions)

Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs
Źródło:
String.Comparison.cs

Porównuje dwa określone String obiekty przy użyciu określonych opcji porównania i informacji specyficznych dla kultury, aby wpłynąć na porównanie, i zwraca liczbę całkowitą, która wskazuje relację dwóch ciągów ze sobą w kolejności sortowania.

public:
 static int Compare(System::String ^ strA, System::String ^ strB, System::Globalization::CultureInfo ^ culture, System::Globalization::CompareOptions options);
public static int Compare (string? strA, string? strB, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
public static int Compare (string strA, string strB, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);
static member Compare : string * string * System.Globalization.CultureInfo * System.Globalization.CompareOptions -> int
Public Shared Function Compare (strA As String, strB As String, culture As CultureInfo, options As CompareOptions) As Integer

Parametry

strA
String

Pierwszy ciąg do porównania.

strB
String

Drugi ciąg do porównania.

culture
CultureInfo

Kultura dostarczająca informacje porównawcze specyficzne dla kultury. Jeśli culture wartość to null, używana jest bieżąca kultura.

options
CompareOptions

Opcje do użycia podczas porównywania (takie jak ignorowanie wielkości liter lub symboli).

Zwraca

32-bitowa liczba całkowita ze znakiem wskazująca relację leksykalną między strA i strB, jak pokazano w poniższej tabeli

Wartość Warunek
Mniej niż zerostrA poprzedza strB kolejność sortowania.
ZerostrA występuje w tej samej pozycji co strB w kolejności sortowania.
Większe od zerastrA następuje strB w kolejności sortowania.

Wyjątki

options nie jest wartością CompareOptions .

Przykłady

Poniższy przykład porównuje dwa ciągi na trzy różne sposoby: Porównanie językowe dla kultury en-US; przy użyciu porównania z uwzględnieniem wielkości liter językowych dla kultury en-US; i przy użyciu porównania porządkowego. Ilustruje to, w jaki sposób trzy metody porównania generują trzy różne wyniki.

using namespace System;
using namespace System::Globalization;

public ref class Example
{
public:
   static void Main()
   {
      String^ string1 = "brother";
      String^ string2 = "Brother";
      String^ relation;
      int result;

      // Cultural (linguistic) comparison.
      result = String::Compare(string1, string2, gcnew CultureInfo("en-US"),
                              CompareOptions::None);
      if (result > 0)
         relation = "comes after";
      else if (result == 0)
         relation = "is the same as";
      else
         relation = "comes before";

      Console::WriteLine("'{0}' {1} '{2}'.",
                        string1, relation, string2);

      // Cultural (linguistic) case-insensitive comparison.
      result = String::Compare(string1, string2, gcnew CultureInfo("en-US"),
                              CompareOptions::IgnoreCase);
      if (result > 0)
         relation = "comes after";
      else if (result == 0)
         relation = "is the same as";
      else
         relation = "comes before";

      Console::WriteLine("'{0}' {1} '{2}'.",
                        string1, relation, string2);

       // Culture-insensitive ordinal comparison.
      result = String::CompareOrdinal(string1, string2);
      if (result > 0)
         relation = "comes after";
      else if (result == 0)
         relation = "is the same as";
      else
         relation = "comes before";

      Console::WriteLine("'{0}' {1} '{2}'.",
                        string1, relation, string2);
   }
};

int main()
{
    Example::Main();
}


// The example produces the following output:
//    'brother' comes before 'Brother'.
//    'brother' is the same as 'Brother'.
//    'brother' comes after 'Brother'.
using System;
using System.Globalization;

public class Example0
{
    public static void Main()
    {
        string string1 = "brother";
        string string2 = "Brother";
        string relation;
        int result;

        // Cultural (linguistic) comparison.
        result = String.Compare(string1, string2, new CultureInfo("en-US"), 
                              CompareOptions.None);
        if (result > 0)
            relation = "comes after";
        else if (result == 0)
            relation = "is the same as";
        else
            relation = "comes before";

        Console.WriteLine("'{0}' {1} '{2}'.", 
                        string1, relation, string2);

        // Cultural (linguistic) case-insensitive comparison.
        result = String.Compare(string1, string2, new CultureInfo("en-US"), 
                              CompareOptions.IgnoreCase);
        if (result > 0)
            relation = "comes after";
        else if (result == 0)
            relation = "is the same as";
        else
            relation = "comes before";

        Console.WriteLine("'{0}' {1} '{2}'.", 
                        string1, relation, string2);
 
        // Culture-insensitive ordinal comparison.
        result = String.CompareOrdinal(string1, string2);
        if (result > 0)
            relation = "comes after";
        else if (result == 0)
            relation = "is the same as";
        else
            relation = "comes before";

        Console.WriteLine("'{0}' {1} '{2}'.", 
                        string1, relation, string2);

        // The example produces the following output:
        //    'brother' comes before 'Brother'.   
        //    'brother' is the same as 'Brother'.
        //    'brother' comes after 'Brother'.
    }
}
open System
open System.Globalization

let string1 = "brother"
let string2 = "Brother"

// Cultural (linguistic) comparison.
let result = String.Compare(string1, string2, CultureInfo "en-US", CompareOptions.None)
let relation =
    if result > 0 then "comes after"
    elif result = 0 then "is the same as"
    else "comes before"

printfn $"'{string1}' {relation} '{string2}'."

// Cultural (linguistic) case-insensitive comparison.
let result2 = String.Compare(string1, string2, CultureInfo "en-US", CompareOptions.IgnoreCase)
let relation2 =
    if result2 > 0 then "comes after"
    elif result2 = 0 then "is the same as"
    else "comes before"

printfn $"'{string1}' {relation2} '{string2}'."

// Culture-insensitive ordinal comparison.
let result3 = String.CompareOrdinal(string1, string2)
let relation3 =
    if result2 > 0 then "comes after"
    elif result2 = 0 then "is the same as"
    else "comes before"

printfn $"'{string1}' {relation} '{string2}'."

// The example produces the following output:
//    'brother' comes before 'Brother'.   
//    'brother' is the same as 'Brother'.
//    'brother' comes after 'Brother'.
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim string1 As String = "brother"
      Dim string2 As String = "Brother"
      Dim relation As String
      Dim result As Integer

      ' Cultural (linguistic) comparison.
      result = String.Compare(string1, string2, _
                              New CultureInfo("en-US"), CompareOptions.None)
      If result > 0 Then
         relation = "comes after"
      ElseIf result = 0 Then
         relation = "is the same as"
      Else
         relation = "comes before"
      End If
      Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)

      ' Cultural (linguistic) case-insensitive comparison.
      result = String.Compare(string1, string2, _
                              New CultureInfo("en-US"), CompareOptions.IgnoreCase)
      If result > 0 Then
         relation = "comes after"
      ElseIf result = 0 Then
         relation = "is the same as"
      Else
         relation = "comes before"
      End If
      Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)

      ' Culture-insensitive ordinal comparison.
      result = String.CompareOrdinal(string1, string2)
      If result > 0 Then
         relation = "comes after"
      ElseIf result = 0 Then
         relation = "is the same as"
      Else
         relation = "comes before"
      End If
      Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)
   End Sub
End Module
' The example produces the following output:
'    'brother' comes before 'Brother'.   
'    'brother' is the same as 'Brother'.
'    'brother' comes after 'Brother'.

Uwagi

Porównanie używa parametru culture do uzyskiwania informacji specyficznych dla kultury, takich jak reguły wielkości liter i kolejność alfabetyczna poszczególnych znaków. Na przykład określona kultura może określać, że niektóre kombinacje znaków mogą być traktowane jako pojedynczy znak, że wielkie i małe litery są porównywane w określony sposób lub że kolejność sortowania znaku zależy od znaków poprzedzających lub podążających za nim.

Przestroga

Metoda została zaprojektowana Compare(String, String, CultureInfo, CompareOptions) głównie do użycia w operacjach sortowania lub alfabetyzowania. Nie należy jej używać, gdy głównym celem wywołania metody jest określenie, czy dwa ciągi są równoważne (czyli gdy celem wywołania metody jest przetestowanie wartości zwracanej wartości zero). Aby określić, czy dwa ciągi są równoważne, wywołaj metodę Equals .

Porównanie można dodatkowo określić za pomocą parametru options , który składa się z co najmniej jednego elementu członkowskiego CompareOptions wyliczenia. Jednak ze względu na to, że celem tej metody jest przeprowadzenie porównania ciągów wrażliwych na kulturę, CompareOptions.Ordinal wartości i CompareOptions.OrdinalIgnoreCase nie mają żadnego wpływu.

Oba comparands mogą mieć wartość null. Z definicji każdy ciąg, w tym String.Empty, porównuje więcej niż odwołanie o wartości null, a dwa odwołania o wartości null są porównywane ze sobą.

Porównanie kończy się po wykryciu nierówności lub gdy zostały porównane oba ciągi. Jeśli jednak dwa ciągi są porównywane równą końcu jednego ciągu, a drugi ciąg ma pozostałe znaki, ciąg z pozostałymi znakami jest uznawany za większy.

Uwagi dotyczące wywoływania

Zestawy znaków zawierają znaki do pominięcia. Są to znaki nieuwzględniane podczas porównywania pod względem językowym lub z uwzględnieniem ustawień kulturowych. Metoda Compare(String, String, CultureInfo, CompareOptions) nie uwzględnia takich znaków podczas przeprowadzania porównania wrażliwego na kulturę. Aby rozpoznać ignorowane znaki w porównaniu, podaj wartość Ordinal lub OrdinalIgnoreCase dla parametru options .

Zobacz też

Dotyczy