次の方法で共有


String.Compare メソッド

定義

指定した 2 つの String オブジェクトを比較し、並べ替え順序での相対位置を示す整数を返します。

オーバーロード

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

指定した比較オプションとカルチャ固有の情報を使用して、指定した 2 つの String オブジェクトの部分文字列を比較し、比較に影響を与え、並べ替え順序で 2 つの部分文字列の関係を示す整数を返します。

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

指定した 2 つの String オブジェクトの部分文字列を比較し、大文字と小文字の区別や、カルチャ固有の情報を使用して比較に影響を与え、並べ替え順序での相対位置を示す整数を返します。

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

指定したルールを使用して、指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序での相対位置を示す整数を返します。

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

指定した 2 つの String オブジェクトの部分文字列を比較し、大文字と小文字を区別または無視し、並べ替え順序での相対位置を示す整数を返します。

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

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序での相対位置を示す整数を返します。

Compare(String, String, CultureInfo, CompareOptions)

指定した比較オプションとカルチャ固有の情報を使用して、指定した 2 つの String オブジェクトを比較し、比較に影響を与え、並べ替え順序で 2 つの文字列の関係を示す整数を返します。

Compare(String, String, Boolean, CultureInfo)

指定した 2 つの String オブジェクトを比較し、そのケースを無視または優先し、カルチャ固有の情報を使用して比較に影響を与え、並べ替え順序での相対位置を示す整数を返します。

Compare(String, String, StringComparison)

指定したルールを使用して、指定した 2 つの String オブジェクトを比較し、並べ替え順序での相対位置を示す整数を返します。

Compare(String, String, Boolean)

指定した 2 つの String オブジェクトを比較し、大文字と小文字を区別または無視し、並べ替え順序での相対位置を示す整数を返します。

Compare(String, String)

指定した 2 つの String オブジェクトを比較し、並べ替え順序での相対位置を示す整数を返します。

注釈

Compare メソッドのすべてのオーバーロードは、2 つの比較子間の字句関係を示す 32 ビット符号付き整数を返します。

価値 条件
0 未満 最初の部分文字列は、並べ替え順序で 2 番目の部分文字列の前にあります。
ゼロ 部分文字列は並べ替え順序で同じ位置に配置されるか、length が 0 です。
0 より大きい 最初の部分文字列は、並べ替え順序で 2 番目の部分文字列の後に続きます。

警告

可能な限り、StringComparison パラメーターを含む Compare メソッドのオーバーロードを呼び出す必要があります。 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。

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

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した比較オプションとカルチャ固有の情報を使用して、指定した 2 つの String オブジェクトの部分文字列を比較し、比較に影響を与え、並べ替え順序で 2 つの部分文字列の関係を示す整数を返します。

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

パラメーター

strA
String

比較で使用する最初の文字列。

indexA
Int32

strA内の部分文字列の開始位置。

strB
String

比較で使用する 2 番目の文字列。

indexB
Int32

strB内の部分文字列の開始位置。

length
Int32

比較する部分文字列内の最大文字数。

culture
CultureInfo

カルチャ固有の比較情報を提供するオブジェクト。 culturenullされている場合は、現在のカルチャが使用されます。

options
CompareOptions

比較を実行するときに使用するオプション (大文字と小文字や記号の無視など)。

戻り値

次の表に示すように、2 つの部分文字列間の字句関係を示す整数。

価値 条件
0 未満 strA 内の部分文字列は、並べ替え順序で strB 部分文字列の前にあります。
ゼロ 部分文字列は並べ替え順序で同じ位置に配置されるか、length が 0 です。
0 より大きい strA の部分文字列は、並べ替え順序で strB 部分文字列の後に続きます。

例外

optionsCompareOptions 値ではありません。

indexAstrA.Lengthより大きいです。

-又は-

indexBstrB.Lengthより大きいです。

-又は-

indexAindexB、または length が負の値です。

-又は-

strA または strBnullされ、length が 0 より大きい。

次の例では、Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) メソッドを使用して、2 人の姓を比較します。 その後、アルファベット順に一覧表示されます。

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

注釈

比較する部分文字列は、indexA 位置と strA 位置 indexB位置の strB で開始します。 最初の部分文字列の長さは、strA - indexAの長さです。 2 番目の部分文字列の長さは、strB から indexBを引いた長さです。

比較する文字数は、2 つの部分文字列の長さが小さくなり、lengthです。 indexAindexB、および length パラメーターは負でない必要があります。

比較では、culture パラメーターを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、特定のカルチャでは、特定の文字の組み合わせを 1 つの文字として扱う、大文字と小文字を特定の方法で比較する、または文字の並べ替え順序が文字の前または後の文字に依存することを指定できます。

注意

Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) メソッドは、主に並べ替えまたはアルファベット順の操作に使用するように設計されています。 メソッド呼び出しの主な目的が、2 つの部分文字列が等しいかどうかを判断する場合 (つまり、メソッド呼び出しの目的が戻り値 0 をテストする場合) には使用しないでください。 2 つの文字列が等しいかどうかを判断するには、Equals メソッドを呼び出します。

strAstrB の一方または両方を nullできます。 定義上、String.Emptyを含むすべての文字列は null 参照より大きい値を比較し、2 つの null 参照は互いに等しく比較されます。

比較は、System.Globalization.CompareOptions 列挙体の 1 つ以上のメンバーで構成される options パラメーターでさらに指定できます。 ただし、このメソッドの目的はカルチャに依存する文字列比較を行うため、CompareOptions.Ordinal 値と CompareOptions.OrdinalIgnoreCase 値は無効です。

この比較は、不等式が検出された場合、または両方の部分文字列が比較されたときに終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合、残りの文字を持つ文字列は大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) メソッドでは、言語的またはカルチャに依存する比較を実行する場合、これらの文字は考慮されません。 比較で無視できる文字を認識するには、options パラメーターに Ordinal または OrdinalIgnoreCase の値を指定します。

こちらもご覧ください

適用対象

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

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した 2 つの String オブジェクトの部分文字列を比較し、大文字と小文字の区別や、カルチャ固有の情報を使用して比較に影響を与え、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較で使用する最初の文字列。

indexA
Int32

strA内の部分文字列の位置。

strB
String

比較で使用する 2 番目の文字列。

indexB
Int32

strB内の部分文字列の位置。

length
Int32

比較する部分文字列内の最大文字数。

ignoreCase
Boolean

比較中に大文字と小文字を区別しない true。それ以外の場合は、falseします。

culture
CultureInfo

カルチャ固有の比較情報を提供するオブジェクト。 culturenullされている場合は、現在のカルチャが使用されます。

戻り値

2 つの比較の構文関係を示す整数。

価値 条件
0 未満 strA 内の部分文字列は、並べ替え順序で strB 部分文字列の前にあります。
ゼロ 部分文字列は並べ替え順序で同じ位置に配置されるか、length が 0 です。
0 より大きい strA の部分文字列は、並べ替え順序で strB 部分文字列の後に続きます。

例外

indexAstrAより大きい。Length.

-又は-

indexBstrBより大きい。Length.

-又は-

indexAindexB、または length が負の値です。

-又は-

strA または strBnullされ、length が 0 より大きい。

次の例では、異なるカルチャを使用して 2 つの部分文字列を比較し、部分文字列の大文字と小文字の区別を無視します。 カルチャの選択は、文字 "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'.
'

注釈

比較する部分文字列は、indexAstrA、および indexBstrB で開始します。 indexAindexB の両方が 0 から始まります。つまり、strA および strB の最初の文字は、位置 1 ではなく 0 の位置にあります。 最初の部分文字列の長さは、strA から indexA + 1 の長さに等しくなります。 2 番目の部分文字列の長さは、strB から indexB + 1 の長さに等しくなります。

比較する文字数は、2 つの部分文字列の長さが小さくなり、lengthです。 indexAindexB、および length パラメーターは負でない必要があります。

比較では、culture パラメーターを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、カルチャでは、特定の文字の組み合わせを 1 つの文字として扱うか、大文字と小文字を特定の方法で比較するか、文字の並べ替え順序が文字の前または後の文字に依存するように指定できます。

比較は、単語の並べ替えルールを使用して実行されます。 単語、文字列、序数の並べ替えの詳細については、System.Globalization.CompareOptionsを参照してください。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

この比較は、不等式が検出された場合、または両方の部分文字列が比較されたときに終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合は、残りの文字を含む文字列の方が大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

序数比較を使用して、パス名を "file" と比較します。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) メソッドでは、言語的またはカルチャに依存する比較を実行する場合、これらの文字は考慮されません。 比較で無視できる文字を認識するには、Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) メソッドを呼び出し、options パラメーターに Ordinal または OrdinalIgnoreCase の値を指定します。

こちらもご覧ください

適用対象

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

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定したルールを使用して、指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較で使用する最初の文字列。

indexA
Int32

strA内の部分文字列の位置。

strB
String

比較で使用する 2 番目の文字列。

indexB
Int32

strB内の部分文字列の位置。

length
Int32

比較する部分文字列内の最大文字数。

comparisonType
StringComparison

比較で使用する規則を指定する列挙値の 1 つ。

戻り値

2 つの比較の構文関係を示す 32 ビット符号付き整数。

価値 条件
0 未満 strA 内の部分文字列は、並べ替え順序で strB 部分文字列の前にあります。
ゼロ 部分文字列は並べ替え順序で同じ位置に配置されるか、length パラメーターが 0 です。
0 より大きい strA の部分文字列は、並べ替え順序で strB 部分文字列の後に続きます。

例外

indexAstrAより大きい。Length.

-又は-

indexBstrBより大きい。Length.

-又は-

indexAindexB、または length が負の値です。

-又は-

indexA または indexBnullされ、length が 0 より大きい。

comparisonTypeStringComparison 値ではありません。

次の例では、2 つの部分文字列を比較します。

// 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'.
'

注釈

比較する部分文字列は、indexAstrAindexBstrB で始まります。 indexAindexB の両方が 0 から始まります。つまり、strA および strB の最初の文字は、位置 1 ではなく 0 の位置にあります。 最初の部分文字列の長さは、strA から indexA + 1 の長さに等しくなります。 2 番目の部分文字列の長さは、strB から indexB + 1 の長さに等しくなります。

比較する文字数は、2 つの部分文字列の長さが小さくなり、lengthです。 indexAindexB、および length パラメーターは負でない必要があります。

comparisonType パラメーターは、比較で現在のカルチャまたはインバリアント カルチャを使用するか、比較対象の大文字と小文字を区別するか無視するか、単語 (カルチャに依存) または序数 (カルチャを区別しない) 並べ替え規則を使用するかを示します。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

この比較は、不等式が検出された場合、または両方の部分文字列が比較されたときに終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合、残りの文字を含む文字列は大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

序数比較を使用して、パス名を "file" と比較します。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, Int32, String, Int32, Int32, StringComparison) メソッドでは、言語的またはカルチャに依存する比較を実行する場合、これらの文字は考慮されません。 比較で無視できる文字を認識するには、comparisonType パラメーターに Ordinal または OrdinalIgnoreCase の値を指定します。

こちらもご覧ください

適用対象

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

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した 2 つの String オブジェクトの部分文字列を比較し、大文字と小文字を区別または無視し、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較で使用する最初の文字列。

indexA
Int32

strA内の部分文字列の位置。

strB
String

比較で使用する 2 番目の文字列。

indexB
Int32

strB内の部分文字列の位置。

length
Int32

比較する部分文字列内の最大文字数。

ignoreCase
Boolean

比較中に大文字と小文字を区別しない true。それ以外の場合は、falseします。

戻り値

2 つの比較の構文関係を示す 32 ビット符号付き整数。

価値 条件
0 未満 strA 内の部分文字列は、並べ替え順序で strB 部分文字列の前にあります。
ゼロ 部分文字列は並べ替え順序で同じ位置に配置されるか、length が 0 です。
0 より大きい strA の部分文字列は、並べ替え順序で strB 部分文字列の後に続きます。

例外

indexAstrAより大きい。Length.

-又は-

indexBstrBより大きい。Length.

-又は-

indexAindexB、または length が負の値です。

-又は-

indexA または indexBnullされ、length が 0 より大きい。

次の例では、大文字と小文字のみが異なる 2 つの部分文字列の 2 つの比較を実行します。 最初の比較では大文字と小文字が無視され、2 番目の比較では大文字と小文字が区別されます。

// 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'.
'

注釈

比較する部分文字列は、indexAstrA、および indexBstrB で開始します。 indexAindexB の両方が 0 から始まります。つまり、strAstrB の最初の文字は位置 0 です。 最初の部分文字列の長さは、strA から indexA + 1 の長さに等しくなります。 2 番目の部分文字列の長さは、strB から indexB + 1 の長さに等しくなります。

比較する文字数は、2 つの部分文字列の長さが小さくなり、lengthです。 indexAindexB、および length パラメーターは負でない必要があります。

比較では、現在のカルチャを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、カルチャでは、特定の文字の組み合わせを 1 つの文字として扱うか、大文字と小文字を特定の方法で比較するか、文字の並べ替え順序が文字の前または後の文字に依存するように指定できます。

比較は、単語の並べ替えルールを使用して実行されます。 単語、文字列、序数の並べ替えの詳細については、System.Globalization.CompareOptionsを参照してください。

警告

文字列を比較するときは、Compare(String, Int32, String, Int32, Int32, StringComparison) メソッドを呼び出す必要があります。そのためには、メソッドが使用する文字列比較の種類を明示的に指定する必要があります。 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

この比較は、不等式が検出された場合、または両方の部分文字列が比較されたときに終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合は、残りの文字を含む文字列の方が大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

パス名は、インバリアント方式で比較する必要があります。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, Int32, String, Int32, Int32, Boolean) メソッドでは、言語的またはカルチャに依存する比較を実行する場合、これらの文字は考慮されません。 比較で無視できる文字を認識するには、Compare(String, Int32, String, Int32, Int32, StringComparison) メソッドを呼び出し、comparisonType パラメーターに Ordinal または OrdinalIgnoreCase の値を指定します。

こちらもご覧ください

適用対象

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

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較で使用する最初の文字列。

indexA
Int32

strA内の部分文字列の位置。

strB
String

比較で使用する 2 番目の文字列。

indexB
Int32

strB内の部分文字列の位置。

length
Int32

比較する部分文字列内の最大文字数。

戻り値

2 つの比較の構文関係を示す 32 ビット符号付き整数。

価値 条件
0 未満 strA 内の部分文字列は、並べ替え順序で strB 部分文字列の前にあります。
ゼロ 部分文字列は並べ替え順序で同じ位置に配置されるか、length が 0 です。
0 より大きい strA の部分文字列は、並べ替え順序で strB 部分文字列の後に続きます。

例外

indexAstrAより大きい。Length.

-又は-

indexBstrBより大きい。Length.

-又は-

indexAindexB、または length が負の値です。

-又は-

indexA または indexBnullされ、length が 0 より大きい。

次の例では、2 つの部分文字列を比較します。

// 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'.
'

注釈

比較する部分文字列は、indexAstrAindexBstrB で始まります。 indexAindexB の両方が 0 から始まります。つまり、strAstrB の最初の文字は位置 0 です。 最初の部分文字列の長さは、strA から indexA + 1 の長さに等しくなります。 2 番目の部分文字列の長さは、strB から indexB + 1 の長さに等しくなります。

比較する文字数は、2 つの部分文字列の長さが小さくなり、lengthです。 indexAindexB、および length パラメーターは負でない必要があります。

比較では、現在のカルチャを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、カルチャでは、特定の文字の組み合わせを 1 つの文字として扱うか、大文字と小文字を特定の方法で比較するか、文字の並べ替え順序が文字の前または後の文字に依存するように指定できます。

比較は、単語の並べ替えルールを使用して実行されます。 単語、文字列、序数の並べ替えの詳細については、System.Globalization.CompareOptionsを参照してください。

警告

文字列を比較するときは、Compare(String, Int32, String, Int32, Int32, StringComparison) メソッドを呼び出す必要があります。そのためには、メソッドが使用する文字列比較の種類を明示的に指定する必要があります。 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

この比較は、不等式が検出された場合、または両方の部分文字列が比較されたときに終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合は、残りの文字を含む文字列の方が大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

序数比較を使用して、パス名を "file" と比較します。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, Int32, String, Int32, Int32) メソッドでは、言語的またはカルチャに依存する比較を実行する場合、これらの文字は考慮されません。 比較で無視できる文字を認識するには、Compare(String, Int32, String, Int32, Int32, StringComparison) メソッドを呼び出し、comparisonType パラメーターに Ordinal または OrdinalIgnoreCase の値を指定します。

こちらもご覧ください

適用対象

Compare(String, String, CultureInfo, CompareOptions)

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した比較オプションとカルチャ固有の情報を使用して、指定した 2 つの String オブジェクトを比較し、比較に影響を与え、並べ替え順序で 2 つの文字列の関係を示す整数を返します。

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

パラメーター

strA
String

比較する最初の文字列。

strB
String

比較する 2 番目の文字列。

culture
CultureInfo

カルチャ固有の比較情報を提供するカルチャ。 culturenullされている場合は、現在のカルチャが使用されます。

options
CompareOptions

比較を実行するときに使用するオプション (大文字と小文字や記号の無視など)。

戻り値

次の表に示すように、strAstrBの間の字句関係を示す 32 ビット符号付き整数

価値 条件
0 未満並べ替え順序で strB の前に strA
ゼロ strA は、並べ替え順序で strB と同じ位置に発生します。
0 より大きい strA は並べ替え順序で strB に従います。

例外

optionsCompareOptions 値ではありません。

次の例では、3 つの異なる方法で 2 つの文字列を比較します。en-US カルチャには言語比較を使用します。en-US カルチャに対して言語的な大文字と小文字を区別した比較を使用する。と序数比較を使用します。 比較の 3 つの方法が 3 つの異なる結果を生成する方法を示します。

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'.

注釈

比較では、culture パラメーターを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、特定のカルチャでは、特定の文字の組み合わせを 1 つの文字として扱う、大文字と小文字を特定の方法で比較する、または文字の並べ替え順序が文字の前または後の文字に依存することを指定できます。

注意

Compare(String, String, CultureInfo, CompareOptions) メソッドは、主に並べ替えまたはアルファベット順の操作に使用するように設計されています。 メソッド呼び出しの主な目的が、2 つの文字列が等しいかどうかを判断する場合 (つまり、メソッド呼び出しの目的が戻り値 0 をテストする場合) には使用しないでください。 2 つの文字列が等しいかどうかを判断するには、Equals メソッドを呼び出します。

比較は、CompareOptions 列挙体の 1 つ以上のメンバーで構成される options パラメーターでさらに指定できます。 ただし、このメソッドの目的はカルチャに依存する文字列比較を行うため、CompareOptions.Ordinal 値と CompareOptions.OrdinalIgnoreCase 値は無効です。

一方または両方の比較を nullできます。 定義上、String.Emptyを含むすべての文字列は null 参照より大きい値を比較し、2 つの null 参照は互いに等しく比較されます。

不等式が検出された場合、または両方の文字列が比較されると、比較は終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合、残りの文字を持つ文字列は大きいと見なされます。

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 Compare(String, String, CultureInfo, CompareOptions) メソッドでは、カルチャに依存する比較を実行するときに、このような文字は考慮されません。 比較で無視できる文字を認識するには、options パラメーターに Ordinal または OrdinalIgnoreCase の値を指定します。

こちらもご覧ください

適用対象

Compare(String, String, Boolean, CultureInfo)

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した 2 つの String オブジェクトを比較し、そのケースを無視または優先し、カルチャ固有の情報を使用して比較に影響を与え、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較する最初の文字列。

strB
String

比較する 2 番目の文字列。

ignoreCase
Boolean

比較中に大文字と小文字を区別しない true。それ以外の場合は、falseします。

culture
CultureInfo

カルチャ固有の比較情報を提供するオブジェクト。 culturenullされている場合は、現在のカルチャが使用されます。

戻り値

2 つの比較の構文関係を示す 32 ビット符号付き整数。

価値 条件
0 未満並べ替え順序で strB の前に strA
ゼロ strA は、並べ替え順序で strB と同じ位置に発生します。
0 より大きい strA は並べ替え順序で strB に従います。

次の例は、カルチャが比較にどのように影響するかを示しています。 チェコ語 - チェコ共和国の文化では、"ch" は "d" より大きい 1 文字です。 ただし、英語 - 米国のカルチャでは、"ch" は 2 つの文字で構成され、"c" は "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
'

注釈

比較では、culture パラメーターを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、カルチャでは、特定の文字の組み合わせを 1 つの文字として扱うか、大文字と小文字を特定の方法で比較するか、文字の並べ替え順序が文字の前または後の文字に依存するように指定できます。

比較は、単語の並べ替えルールを使用して実行されます。 単語、文字列、序数の並べ替えの詳細については、System.Globalization.CompareOptionsを参照してください。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

不等式が検出された場合、または両方の文字列が比較されると、比較は終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合は、残りの文字を含む文字列の方が大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

序数比較を使用して、パス名を "file" と比較します。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, String, Boolean, CultureInfo) メソッドでは、カルチャに依存する比較を実行するときに、このような文字は考慮されません。 たとえば、次のコードが .NET Framework 4 以降で実行されている場合、インバリアント カルチャを使用した "animal" と "Ani-mal" (ソフト ハイフンまたは U+00AD を使用) の大文字と小文字を区別しない比較は、2 つの文字列が同等であることを示します。

  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

文字列比較で無視できる文字を認識するには、Compare(String, String, CultureInfo, CompareOptions) メソッドを呼び出し、options パラメーターに Ordinal または OrdinalIgnoreCase のいずれかの値を指定します。

こちらもご覧ください

適用対象

Compare(String, String, StringComparison)

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定したルールを使用して、指定した 2 つの String オブジェクトを比較し、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較する最初の文字列。

strB
String

比較する 2 番目の文字列。

comparisonType
StringComparison

比較で使用する規則を指定する列挙値の 1 つ。

戻り値

2 つの比較の構文関係を示す 32 ビット符号付き整数。

価値 条件
0 未満並べ替え順序で strB の前に strA
ゼロ strA は、並べ替え順序で strB と同じ位置にあります。
0 より大きい strA は並べ替え順序で strB に従います。

例外

comparisonTypeStringComparison 値ではありません。

StringComparison はサポートされていません。

次の例では、文字 "I" の 3 つのバージョンを比較します。 結果は、カルチャの選択、大文字と小文字の区別が無視されるかどうか、および序数比較が実行されるかどうかによって影響を受けます。

// 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)
'

注釈

comparisonType パラメーターは、比較で現在のカルチャまたはインバリアント カルチャを使用するか、比較対象の大文字と小文字を区別するか無視するか、単語 (カルチャに依存) または序数 (カルチャを区別しない) 並べ替え規則を使用するかを示します。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

不等式が検出された場合、または両方の文字列が比較されると、比較は終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合、残りの文字を含む文字列は大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

序数比較を使用して、パス名を "file" と比較します。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, String, StringComparison) メソッドでは、カルチャに依存する比較を実行するときに、このような文字は考慮されません。 比較で無視できる文字を認識するには、comparisonType パラメーターに Ordinal または OrdinalIgnoreCase の値を指定します。

こちらもご覧ください

適用対象

Compare(String, String, Boolean)

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した 2 つの String オブジェクトを比較し、大文字と小文字を区別または無視し、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較する最初の文字列。

strB
String

比較する 2 番目の文字列。

ignoreCase
Boolean

比較中に大文字と小文字を区別しない true。それ以外の場合は、falseします。

戻り値

2 つの比較の構文関係を示す 32 ビット符号付き整数。

価値 条件
0 未満並べ替え順序で strB の前に strA
ゼロ strA は、並べ替え順序で strB と同じ位置に発生します。
0 より大きい strA は並べ替え順序で strB に従います。

次の例は、Compare(String, String, Boolean) メソッドが文字列を比較するときに ToUpper または ToLower を使用することと同じであることを示しています。

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

注釈

比較では、現在のカルチャを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、カルチャでは、特定の文字の組み合わせを 1 つの文字として扱うか、大文字と小文字を特定の方法で比較するか、文字の並べ替え順序が文字の前または後の文字に依存するように指定できます。

比較は、単語の並べ替えルールを使用して実行されます。 単語、文字列、序数の並べ替えの詳細については、System.Globalization.CompareOptionsを参照してください。

警告

文字列を比較するときは、Compare(String, String, StringComparison) メソッドを呼び出す必要があります。そのためには、メソッドが使用する文字列比較の種類を明示的に指定する必要があります。 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

不等式が検出された場合、または両方の文字列が比較されると、比較は終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合は、残りの文字を含む文字列の方が大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

序数比較を使用して、パス名を "file" と比較します。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, String, Boolean) メソッドでは、カルチャに依存する比較を実行するときに、このような文字は考慮されません。 たとえば、カルチャに依存し、大文字と小文字を区別しない "animal" と "Ani-mal" の比較 (ソフト ハイフンまたは U+00AD を使用) は、2 つの文字列が同等であることを示します。

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

文字列比較で無視できる文字を認識するには、Compare(String, String, StringComparison) メソッドを呼び出し、comparisonType パラメーターに Ordinal または OrdinalIgnoreCase のいずれかの値を指定します。

こちらもご覧ください

適用対象

Compare(String, String)

ソース:
String.Comparison.cs
ソース:
String.Comparison.cs
ソース:
String.Comparison.cs

指定した 2 つの String オブジェクトを比較し、並べ替え順序での相対位置を示す整数を返します。

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

パラメーター

strA
String

比較する最初の文字列。

strB
String

比較する 2 番目の文字列。

戻り値

2 つの比較の構文関係を示す 32 ビット符号付き整数。

価値 条件
0 未満並べ替え順序で strB の前に strA
ゼロ strA は、並べ替え順序で strB と同じ位置に発生します。
0 より大きい strA は並べ替え順序で strB に従います。

次の例では、Compare(String, String) メソッドを呼び出して、3 つの文字列セットを比較します。

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

次の例では、ReverseStringComparer クラスは、Compare メソッドを使用して 2 つの文字列を評価する方法を示しています。

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

注釈

比較では、現在のカルチャを使用して、大文字と小文字の規則や個々の文字のアルファベット順などのカルチャ固有の情報を取得します。 たとえば、カルチャでは、特定の文字の組み合わせを 1 つの文字として扱うか、大文字と小文字を特定の方法で比較するか、文字の並べ替え順序が文字の前または後の文字に依存するように指定できます。

比較は、単語の並べ替えルールを使用して実行されます。 単語、文字列、序数の並べ替えの詳細については、System.Globalization.CompareOptionsを参照してください。

警告

文字列を比較するときは、Compare(String, String, StringComparison) メソッドを呼び出す必要があります。そのためには、メソッドが使用する文字列比較の種類を明示的に指定する必要があります。 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。

一方または両方の比較を nullできます。 定義上、空の文字列 ("") を含むすべての文字列は、null 参照より大きい値を比較します。2 つの null 参照が互いに等しく比較されます。

不等式が検出された場合、または両方の文字列が比較されると、比較は終了します。 ただし、2 つの文字列が 1 つの文字列の末尾と等しく比較され、もう一方の文字列に残りの文字がある場合は、残りの文字を含む文字列の方が大きいと見なされます。 戻り値は、最後に実行された比較の結果です。

カルチャ固有の大文字と小文字の区別規則によって比較が影響を受けると、予期しない結果が発生する可能性があります。 たとえば、トルコ語では、次の例では、トルコ語のファイル システムが "file" の文字 "i" に言語的な大文字と小文字の規則を使用しないため、間違った結果が生成されます。

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

序数比較を使用して、パス名を "file" と比較します。 これを行う正しいコードは次のとおりです。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。 Compare(String, String) メソッドでは、カルチャに依存する比較を実行するときに、このような文字は考慮されません。 たとえば、次のコードが .NET Framework 4 以降で実行されている場合、カルチャに依存する "animal" と "ani-mal" の比較 (ソフト ハイフンまたは U+00AD を使用) は、2 つの文字列が同等であることを示します。

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

文字列比較で無視できる文字を認識するには、Compare(String, String, StringComparison) メソッドを呼び出し、comparisonType パラメーターに Ordinal または OrdinalIgnoreCase のいずれかの値を指定します。

こちらもご覧ください

適用対象