String.Compare String.Compare String.Compare String.Compare Method

定義

指定した 2 つの String オブジェクトを比較し、それらの相対位置を並べ替え順序で示す整数を返します。Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

オーバーロード

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

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを設定できます。Compares substrings of two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

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

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを指定し、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

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

指定した規則を使用して、指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。Compares substrings of two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

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

指定した 2 つの String オブジェクトの部分文字列を比較し、それらの相対位置を並べ替え順序で示す整数を返します。Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

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

指定した 2 つの String オブジェクトの部分文字列を比較し、2 つの部分文字列の互いのリレーションシップを並べ替え順序で示す整数を返します。比較時に、指定した比較オプションと、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order.

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

指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを指定し、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares two specified String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

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

指定した規則を使用して、指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。Compares two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

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

指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを設定できます。Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

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

指定した 2 つの String オブジェクトを比較し、それらの相対位置を並べ替え順序で示す整数を返します。Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

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

指定した 2 つの String オブジェクトを比較し、2 つの文字列の互いのリレーションシップを並べ替え順序で示す整数を返します。比較時に、指定した比較オプションと、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two strings to each other in the sort order.

注釈

Compare メソッドのすべてのオーバーロードは、2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数を返します。All overloads of the Compare method return a 32-bit signed integer indicating the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero 2 番目の部分文字列の前に、並べ替え順で最初の部分文字列。The first substring precedes the second substring in the sort order.
0Zero 部分文字列は並べ替え順序で同じ位置で発生するか、length はゼロです。The substrings occur in the same position in the sort order, or length is zero.
0 より大きい値Greater than zero 最初の部分文字列では、並べ替え順序で 2 番目の部分文字列に従います。The first substring follows the second substring in the sort order.

警告

可能であればのオーバー ロードを呼び出す必要があります、Compareメソッドを含む、StringComparisonパラメーター。Whenever possible, you should call an overload of the Compare method that includes a StringComparison parameter. 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。For more information, see Best Practices for Using Strings.

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

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを設定できます。Compares substrings of two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

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

比較で使用する最初の文字列。The first string to use in the comparison.

indexA
Int32 Int32 Int32 Int32

strA 内の部分文字列の位置。The position of the substring within strA.

strB
String String String String

比較で使用する 2 番目の文字列。The second string to use in the comparison.

indexB
Int32 Int32 Int32 Int32

strB 内の部分文字列の位置。The position of the substring within strB.

length
Int32 Int32 Int32 Int32

比較する各部分文字列の最大文字数。The maximum number of characters in the substrings to compare.

ignoreCase
Boolean Boolean Boolean Boolean

比較時に大文字と小文字の区別を無視する場合は true。それ以外の場合は falsetrue to ignore case during the comparison; otherwise, false.

戻り値

2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数。A 32-bit signed integer that indicates the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero strA 内の部分文字列は strB 内の部分文字列に並べ替え順序において先行します。The substring in strA precedes the substring in strB in the sort order.
0Zero 部分文字列は並べ替え順序で同じ位置で発生するか、length はゼロです。The substrings occur in the same position in the sort order, or length is zero.
0 より大きい値Greater than zero 並べ替え順序で、strA 内の部分文字列は strB 内の部分文字列の後ろになります。The substring in strA follows the substring in strB in the sort order.

例外

indexAstrA.Length より大きくなっています。indexA is greater than strA.Length.

または-or- indexBstrB.Length より大きくなっています。indexB is greater than strB.Length.

または-or- indexAindexB、または length が負の値です。indexA, indexB, or length is negative.

または-or- indexA または indexB のいずれかが null であり、length が 0 より大きいです。Either indexA or indexB is null, and length is greater than zero.

次の例では、場合のみが異なる 2 つの部分文字列の 2 つの比較を実行します。The following example performs two comparisons of two substrings that only differ in case. 大文字小文字が、最初に比較と、2 つ目の比較では大文字です。The first comparison ignores case and the second comparison considers case.

// 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'.
*/
// Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean)
using System;

class Sample {
    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:");
    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'.
*/
' Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean)
Imports System
Imports Microsoft.VisualBasic

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 'Main
End Class 'Sample
'
'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'.
'

注釈

比較する部分文字列の開始strAindexA、およびstrBindexBします。The substrings to compare start in strA at indexA, and in strB at indexB. 両方indexAindexBは 0 から始まる。 つまり、最初の文字strAstrBが 0 の位置。Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero. 最初の部分文字列の長さがの長さと等しいstrAマイナスindexA1 を加算します。The length of the first substring is equal to the length of strA minus indexA plus one. 2 番目の部分文字列の長さがの長さと等しいstrBマイナスindexB1 を加算します。The length of the second substring is equal to the length of strB minus indexB plus one.

比較する文字の数が 2 つの部分文字列の長さのうちの小さい方とlengthします。The number of characters to compare is the lesser of the lengths of the two substrings, and length. indexAindexB、およびlengthパラメーターは、0 以上である必要があります。The indexA, indexB, and length parameters must be nonnegative.

比較では、現在のカルチャを使用して、個々 の文字のアルファベット順、大文字小文字の規則などのカルチャに固有の情報を取得します。The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. たとえば、カルチャが特定の文字の組み合わせが単一の文字として扱うか、特定の方法では、大文字と小文字を比較することを指定できますまたは文字の前に、文字の並べ替え順序が依存しているかそれに従います。For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

比較は、単語の並べ替え規則を使用して実行されます。The comparison is performed using word sort rules. 単語、文字列、および序数の並べ替えの詳細については、次を参照してください。System.Globalization.CompareOptionsします。For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

警告

文字列を比較するときに呼び出す必要があります、Compare(String, Int32, String, Int32, Int32, StringComparison)メソッドで、明示的にメソッドを使用する文字列比較の種類を指定する必要があります。When comparing strings, you should call the Compare(String, Int32, String, Int32, Int32, StringComparison) method, which requires that you explicitly specify the type of string comparison that the method uses. 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。For more information, see Best Practices for Using Strings.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の部分文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both substrings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合、残りの文字を含む文字列が大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

パス名は、インバリアントの方法で比較する必要があります。The path name needs to be compared in an invariant manner. これを行う適切なコードは次のとおりです。The correct code to do this is as follows.

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, Int32, String, Int32, Int32, Boolean)言語またはカルチャに依存した比較を実行するときに、メソッドでこれらの文字が考慮されません。The Compare(String, Int32, String, Int32, Int32, Boolean) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 比較で無視できる文字を認識するように呼び出す、Compare(String, Int32, String, Int32, Int32, StringComparison)メソッドの値を指定してOrdinalまたはOrdinalIgnoreCasecomparisonTypeパラメーター。To recognize ignorable characters in your comparison, call the Compare(String, Int32, String, Int32, Int32, StringComparison) method and supply a value of Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

こちらもご覧ください

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

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを指定し、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

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

比較で使用する最初の文字列。The first string to use in the comparison.

indexA
Int32 Int32 Int32 Int32

strA 内の部分文字列の位置。The position of the substring within strA.

strB
String String String String

比較で使用する 2 番目の文字列。The second string to use in the comparison.

indexB
Int32 Int32 Int32 Int32

strB 内の部分文字列の位置。The position of the substring within strB.

length
Int32 Int32 Int32 Int32

比較する各部分文字列の最大文字数。The maximum number of characters in the substrings to compare.

ignoreCase
Boolean Boolean Boolean Boolean

比較時に大文字と小文字の区別を無視する場合は true。それ以外の場合は falsetrue to ignore case during the comparison; otherwise, false.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

カルチャ固有の比較情報を提供するオブジェクト。An object that supplies culture-specific comparison information.

戻り値

2 つの比較対照値の構文上の関係を示す整数。An integer that indicates the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero strA 内の部分文字列は strB 内の部分文字列に並べ替え順序において先行します。The substring in strA precedes the substring in strB in the sort order.
0Zero 部分文字列は並べ替え順序で同じ位置で発生するか、length はゼロです。The substrings occur in the same position in the sort order, or length is zero.
0 より大きい値Greater than zero 並べ替え順序で、strA 内の部分文字列は strB 内の部分文字列の後ろになります。The substring in strA follows the substring in strB in the sort order.

例外

indexAstrA.Length より大きくなっています。indexA is greater than strA.Length.

または-or- indexBstrB.Length より大きくなっています。indexB is greater than strB.Length.

または-or- indexAindexB、または length が負の値です。indexA, indexB, or length is negative.

または-or- strA または strB のいずれかが null であり、length が 0 を超えています。Either strA or strB is null, and length is greater than zero.

次の例では、異なるカルチャを使用して、部分文字列の大文字と小文字を無視して 2 つの部分文字列を比較します。The following example compares two substrings using different cultures and ignoring the case of the substrings. 選択したカルチャに影響が"I"の文字方法と比較します。The choice of culture affects how the letter "I" is compared.

// 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 Sample {
    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)
Imports System
Imports System.Globalization
Imports Microsoft.VisualBasic

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 'Main
End Class 'Sample
'
'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'.
'

注釈

比較する部分文字列の開始strAindexA、およびstrBindexBします。The substrings to compare start in strA at indexA, and in strB at indexB. 両方indexAindexBは 0 から始まる。 つまり、最初の文字strAstrBで位置の 0、1 つ配置できません。Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero, not position one. 最初の部分文字列の長さがの長さと等しいstrAマイナスindexA1 を加算します。The length of the first substring is equal to the length of strA minus indexA plus one. 2 番目の部分文字列の長さがの長さと等しいstrBマイナスindexB1 を加算します。The length of the second substring is equal to the length of strB minus indexB plus one.

比較する文字の数が 2 つの部分文字列の長さのうちの小さい方とlengthします。The number of characters to compare is the lesser of the lengths of the two substrings, and length. indexAindexB、およびlengthパラメーターは、0 以上である必要があります。The indexA, indexB, and length parameters must be nonnegative.

比較を使用して、culture個々 の文字のアルファベット順、大文字小文字の規則などのカルチャに固有の情報を取得するパラメーター。The comparison uses the culture parameter to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. たとえば、カルチャが特定の文字の組み合わせが単一の文字として扱うか、特定の方法では、大文字と小文字を比較することを指定できますまたは文字の前に、文字の並べ替え順序が依存しているかそれに従います。For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

比較は、単語の並べ替え規則を使用して実行されます。The comparison is performed using word sort rules. 単語、文字列、および序数の並べ替えの詳細については、次を参照してください。System.Globalization.CompareOptionsします。For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の部分文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both substrings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合、残りの文字を含む文字列が大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

序数に基づく比較を使用して、「ファイル」へのパス名を比較します。Compare the path name to "file" using an ordinal comparison. これを行う適切なコードは次のとおりです。The correct code to do this is as follows:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)言語またはカルチャに依存した比較を実行するときに、メソッドでこれらの文字が考慮されません。The Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 比較で無視できる文字を認識するように呼び出す、Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)メソッドの値を指定してOrdinalまたはOrdinalIgnoreCaseoptionsパラメーター。To recognize ignorable characters in your comparison, call the Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method and supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

こちらもご覧ください

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

指定した規則を使用して、指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。Compares substrings of two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

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

比較で使用する最初の文字列。The first string to use in the comparison.

indexA
Int32 Int32 Int32 Int32

strA 内の部分文字列の位置。The position of the substring within strA.

strB
String String String String

比較で使用する 2 番目の文字列。The second string to use in the comparison.

indexB
Int32 Int32 Int32 Int32

strB 内の部分文字列の位置。The position of the substring within strB.

length
Int32 Int32 Int32 Int32

比較する各部分文字列の最大文字数。The maximum number of characters in the substrings to compare.

comparisonType
StringComparison StringComparison StringComparison StringComparison

比較で使用する規則を指定する列挙値の 1 つ。One of the enumeration values that specifies the rules to use in the comparison.

戻り値

2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数。A 32-bit signed integer that indicates the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero strA 内の部分文字列は strB 内の部分文字列に並べ替え順序において先行します。The substring in strA precedes the substring in strB in the sort order.
0Zero 部分文字列は並べ替え順序で同じ位置に出現するか、length パラメーターはゼロです。The substrings occur in the same position in the sort order, or the length parameter is zero.
0 より大きい値Greater than zero 並べ替え順序で、strA 内の部分文字列は strB 内の部分文字列の後ろになります。The substring in strA follows the substring in strB in the sort order.

例外

indexAstrA.Length より大きくなっています。indexA is greater than strA.Length.

または-or- indexBstrB.Length より大きくなっています。indexB is greater than strB.Length.

または-or- indexAindexB、または length が負の値です。indexA, indexB, or length is negative.

または-or- indexA または indexB のいずれかが null であり、length が 0 より大きいです。Either indexA or indexB is null, and length is greater than zero.

comparisonTypeStringComparison 値ではありません。comparisonType is not a StringComparison value.

次の例では、2 つの部分文字列を比較します。The following example compares two substrings.

// 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'.
*/
// Sample for String.Compare(String, Int32, String, Int32, Int32)
using System;

class Sample {
    public static void 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) ? "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'.
*/
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Imports System
Imports Microsoft.VisualBasic

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 'Main
End Class 'Sample
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'

注釈

比較する部分文字列の開始strAindexAstrBindexBします。The substrings to compare start in strA at indexA and in strB at indexB. 両方indexAindexBは 0 から始まる。 つまり、最初の文字strAstrBで位置の 0、1 つ配置できません。Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero, not position one. 最初の部分文字列の長さがの長さと等しいstrAマイナスindexA1 を加算します。The length of the first substring is equal to the length of strA minus indexA plus one. 2 番目の部分文字列の長さがの長さと等しいstrBマイナスindexB1 を加算します。The length of the second substring is equal to the length of strB minus indexB plus one.

比較する文字の数が 2 つの部分文字列の長さのうちの小さい方とlengthします。The number of characters to compare is the lesser of the lengths of the two substrings, and length. indexAindexB、およびlengthパラメーターは、0 以上である必要があります。The indexA, indexB, and length parameters must be nonnegative.

comparisonTypeパラメーターは、比較では、現在またはインバリアント カルチャを使用する必要があります、かどうかを優先または、比較対照値の大文字と小文字を無視または word (カルチャ) を使用して、ことを示します。 または、序数 (カルチャに依存しない) の並べ替え規則。The comparisonType parameter indicates whether the comparison should use the current or invariant culture, honor or ignore the case of the comparands, or use word (culture-sensitive) or ordinal (culture-insensitive) sort rules.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の部分文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both substrings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合に残りの文字の文字列は大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

序数に基づく比較を使用して、「ファイル」へのパス名を比較します。Compare the path name to "file" using an ordinal comparison. これを行う適切なコードは次のとおりです。The correct code to do this is as follows:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, Int32, String, Int32, Int32, StringComparison)言語またはカルチャに依存した比較を実行するときに、メソッドでこれらの文字が考慮されません。The Compare(String, Int32, String, Int32, Int32, StringComparison) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 比較で無視できる文字を認識するように、値を与えるOrdinalまたはOrdinalIgnoreCasecomparisonTypeパラメーター。To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

こちらもご覧ください

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

指定した 2 つの String オブジェクトの部分文字列を比較し、それらの相対位置を並べ替え順序で示す整数を返します。Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

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

比較で使用する最初の文字列。The first string to use in the comparison.

indexA
Int32 Int32 Int32 Int32

strA 内の部分文字列の位置。The position of the substring within strA.

strB
String String String String

比較で使用する 2 番目の文字列。The second string to use in the comparison.

indexB
Int32 Int32 Int32 Int32

strB 内の部分文字列の位置。The position of the substring within strB.

length
Int32 Int32 Int32 Int32

比較する各部分文字列の最大文字数。The maximum number of characters in the substrings to compare.

戻り値

2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数。A 32-bit signed integer indicating the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero strA 内の部分文字列は strB 内の部分文字列に並べ替え順序において先行します。The substring in strA precedes the substring in strB in the sort order.
0Zero 部分文字列は並べ替え順序で同じ位置で発生するか、length はゼロです。The substrings occur in the same position in the sort order, or length is zero.
0 より大きい値Greater than zero 並べ替え順序で、strA 内の部分文字列は strB 内の部分文字列の後ろになります。The substring in strA follows the substring in strB in the sort order.

例外

indexAstrA.Length より大きくなっています。indexA is greater than strA.Length.

または-or- indexBstrB.Length より大きくなっています。indexB is greater than strB.Length.

または-or- indexAindexB、または length が負の値です。indexA, indexB, or length is negative.

または-or- indexA または indexB のいずれかが null であり、length が 0 より大きいです。Either indexA or indexB is null, and length is greater than zero.

次の例では、2 つの部分文字列を比較します。The following example compares two substrings.

// 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'.
*/
// Sample for String.Compare(String, Int32, String, Int32, Int32)
using System;

class Sample {
    public static void 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) ? "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'.
*/
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Imports System
Imports Microsoft.VisualBasic

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 'Main
End Class 'Sample
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'

注釈

比較する部分文字列の開始strAindexAstrBindexBします。The substrings to compare start in strA at indexA and in strB at indexB. 両方indexAindexBは 0 から始まる。 つまり、最初の文字strAstrBが 0 の位置。Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero. 最初の部分文字列の長さがの長さと等しいstrAマイナスindexA1 を加算します。The length of the first substring is equal to the length of strA minus indexA plus one. 2 番目の部分文字列の長さがの長さと等しいstrBマイナスindexB1 を加算します。The length of the second substring is equal to the length of strB minus indexB plus one.

比較する文字の数が 2 つの部分文字列の長さのうちの小さい方とlengthします。The number of characters to compare is the lesser of the lengths of the two substrings, and length. indexAindexB、およびlengthパラメーターは、0 以上である必要があります。The indexA, indexB, and length parameters must be nonnegative.

比較では、現在のカルチャを使用して、個々 の文字のアルファベット順、大文字小文字の規則などのカルチャに固有の情報を取得します。The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. たとえば、カルチャが特定の文字の組み合わせが単一の文字として扱うか、特定の方法では、大文字と小文字を比較することを指定できますまたは文字の前に、文字の並べ替え順序が依存しているかそれに従います。For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

比較は、単語の並べ替え規則を使用して実行されます。The comparison is performed using word sort rules. 単語、文字列、および序数の並べ替えの詳細については、次を参照してください。System.Globalization.CompareOptionsします。For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

警告

文字列を比較するときに呼び出す必要があります、Compare(String, Int32, String, Int32, Int32, StringComparison)メソッドで、明示的にメソッドを使用する文字列比較の種類を指定する必要があります。When comparing strings, you should call the Compare(String, Int32, String, Int32, Int32, StringComparison) method, which requires that you explicitly specify the type of string comparison that the method uses. 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。For more information, see Best Practices for Using Strings.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の部分文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both substrings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合、残りの文字を含む文字列が大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

序数に基づく比較を使用して、「ファイル」へのパス名を比較します。Compare the path name to "file" using an ordinal comparison. これを行う適切なコードは次のとおりです。The correct code to do this is as follows:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, Int32, String, Int32, Int32)言語またはカルチャに依存した比較を実行するときに、メソッドでこれらの文字が考慮されません。The Compare(String, Int32, String, Int32, Int32) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 比較で無視できる文字を認識するように呼び出す、Compare(String, Int32, String, Int32, Int32, StringComparison)メソッドの値を指定してOrdinalまたはOrdinalIgnoreCasecomparisonTypeパラメーター。To recognize ignorable characters in your comparison, call the Compare(String, Int32, String, Int32, Int32, StringComparison) method and supply a value of Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

こちらもご覧ください

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

指定した 2 つの String オブジェクトの部分文字列を比較し、2 つの部分文字列の互いのリレーションシップを並べ替え順序で示す整数を返します。比較時に、指定した比較オプションと、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order.

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

比較で使用する最初の文字列。The first string to use in the comparison.

indexA
Int32 Int32 Int32 Int32

strA 内の部分文字列の開始位置。The starting position of the substring within strA.

strB
String String String String

比較で使用する 2 番目の文字列。The second string to use in the comparison.

indexB
Int32 Int32 Int32 Int32

strB 内の部分文字列の開始位置。The starting position of the substring within strB.

length
Int32 Int32 Int32 Int32

比較する各部分文字列の最大文字数。The maximum number of characters in the substrings to compare.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

カルチャ固有の比較情報を提供するオブジェクト。An object that supplies culture-specific comparison information.

options
CompareOptions CompareOptions CompareOptions CompareOptions

比較の実行時に使用するオプション (大文字と小文字の違いや記号を無視するなど)。Options to use when performing the comparison (such as ignoring case or symbols).

戻り値

2 つの部分文字列の構文上の関係を示す整数。次の表を参照してください。An integer that indicates the lexical relationship between the two substrings, as shown in the following table.

[値]Value 条件Condition
0 より小さい値Less than zero strA 内の部分文字列は strB 内の部分文字列に並べ替え順序において先行します。The substring in strA precedes the substring in strB in the sort order.
0Zero 部分文字列は並べ替え順序で同じ位置で発生するか、length はゼロです。The substrings occur in the same position in the sort order, or length is zero.
0 より大きい値Greater than zero 並べ替え順序で、strA 内の部分文字列は strB 内の部分文字列の後ろになります。The substring in strA follows the substring in strB in the sort order.

例外

optionsCompareOptions 値ではありません。options is not a CompareOptions value.

indexAstrA.Length より大きいです。indexA is greater than strA.Length.

または-or- indexBstrB.Length より大きいです。indexB is greater than strB.Length.

または-or- indexAindexB、または length が負の値です。indexA, indexB, or length is negative.

または-or- strA または strB のいずれかが null であり、length が 0 を超えています。Either strA or strB is null, and length is greater than zero.

次の例では、 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 2 人のユーザーの姓を比較するメソッド。The following example uses the Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method to compare the last names of two people. 次にアルファベット順に表示されます。It then lists them in alphabetical order.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string name1 = "Jack Smith";
      string name2 = "John Doe";
      
      // Get position of space character.
      int index1 = name1.IndexOf(" ");
      index1 = index1 < 0 ? 0 : index1--;
      
      int index2 = name2.IndexOf(" ");
      index1 = index1 < 0 ? 0 : index1--;
      
      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
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

注釈

比較する部分文字列の開始strA位置にあるindexAstrB位置にあるindexBします。The substrings to compare start in strA at position indexA and in strB at position indexB. 最初の部分文字列の長さがの長さstrAマイナスindexAします。The length of the first substring is the length of strA minus indexA. 2 番目の部分文字列の長さは、の長さstrBマイナスindexBします。The length of the second substring is the length of strB minus indexB.

比較する文字の数が 2 つの部分文字列の長さのうちの小さい方とlengthします。The number of characters to compare is the lesser of the lengths of the two substrings, and length. indexAindexB、およびlengthパラメーターは、0 以上である必要があります。The indexA, indexB, and length parameters must be nonnegative.

比較を使用して、cultureパラメーターを個々 の文字のアルファベット順、大文字小文字の規則など、カルチャに固有の情報を取得します。The comparison uses the culture parameter to obtain culture-specific information, such as casing rules and the alphabetical order of individual characters. たとえば、特定のカルチャは、特定の文字の組み合わせを 1 つの文字として扱うことで、特定の方法で大文字と小文字を比較することを指定できますまたは文字の並べ替え順序の文字が依存しているを前または後します。For example, a particular culture could specify that certain combinations of characters be treated as a single character, that uppercase and lowercase characters be compared in a particular way, or that the sort order of a character depends on the characters that precede or follow it.

注意事項

Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)メソッドが並べ替え操作をアルファベット順に並べ替えに使用する主な設計されています。The Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method is designed primarily for use in sorting or alphabetizing operations. また、メソッドの呼び出しの主な目的は、(メソッド呼び出しでは、戻り値が 0 のテスト) の場合は、2 つの部分文字列が等しいかどうかを判断するときにない使用する必要があります。It should not be used when the primary purpose of the method call is to determine whether two substrings are equivalent (that is, when the purpose of the method call is to test for a return value of zero). 2 つの文字列が等しいかどうかを確認するのには、呼び出し、Equalsメソッド。To determine whether two strings are equivalent, call the Equals method.

いずれかまたは両方のstrAstrBできるnullします。One or both of strA and strB can be null. 定義上、任意の文字列を含むString.Empty、互いに等しくない比較に null 参照より大きく、2 つの null 参照を比較します。By definition, any string, including String.Empty, compares greater than a null reference, and two null references compare equal to each other.

によってさらに、比較を指定することができます、optionsパラメーターは、1 つ以上のメンバーで構成される、System.Globalization.CompareOptions列挙体。The comparison can be further specified by the options parameter, which consists of one or more members of the System.Globalization.CompareOptions enumeration. ただし、このメソッドの目的は、カルチャに依存した文字列比較を実行するため、CompareOptions.OrdinalCompareOptions.OrdinalIgnoreCase値は影響ありません。However, because the purpose of this method is to conduct a culture-sensitive string comparison, the CompareOptions.Ordinal and CompareOptions.OrdinalIgnoreCase values have no effect.

比較では、非等値が検出されるか、両方の部分文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both substrings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合に、残りの文字の文字列は大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with the remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)言語またはカルチャに依存した比較を実行するときに、メソッドでこれらの文字が考慮されません。The Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 比較で無視できる文字を認識するように、値を与えるOrdinalまたはOrdinalIgnoreCaseoptionsパラメーター。To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

こちらもご覧ください

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

指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを指定し、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares two specified String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

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

比較する最初の文字列。The first string to compare.

strB
String String String String

比較する 2 番目の文字列。The second string to compare.

ignoreCase
Boolean Boolean Boolean Boolean

比較時に大文字と小文字の区別を無視する場合は true。それ以外の場合は falsetrue to ignore case during the comparison; otherwise, false.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

カルチャ固有の比較情報を提供するオブジェクト。An object that supplies culture-specific comparison information.

戻り値

2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数。A 32-bit signed integer that indicates the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero 並べ替え順序において strAstrB の前になります。strA precedes strB in the sort order.
0Zero strA は並べ替え順序で、strB と同じ位置に出現します。strA occurs in the same position as strB in the sort order.
0 より大きい値Greater than zero 並べ替え順序において strAstrB の後ろになります。strA follows strB in the sort order.

例外

次の例では、カルチャが比較に影響を及ぼすを示します。The following example demonstrates how culture can affect a comparison. チェコ語、チェコ共和国のカルチャでは、"ch"は、"d"よりも大きい 1 つの文字です。In Czech - Czech Republic culture, "ch" is a single character that is greater than "d". ただし、英語 - 米国のカルチャでは"ch という"2 つの文字から成る、"c"は"d"より小さい。However, in English - United States culture, "ch" consists of two characters, and "c" is less than "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
*/
using System;
using System.Globalization;

class Sample {
    public static void Main() {
    String str1 = "change";
    String str2 = "dollar";
    String relation = null;

    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
*/
Imports System
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 'Main
   
   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 'Sample
'
'This example produces the following results.
'For en-US: change < dollar
'For cs-CZ: change > dollar
'

注釈

比較を使用して、culture個々 の文字のアルファベット順、大文字小文字の規則などのカルチャに固有の情報を取得するパラメーター。The comparison uses the culture parameter to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. たとえば、カルチャが特定の文字の組み合わせが単一の文字として扱うか、特定の方法では、大文字と小文字を比較することを指定できますまたは文字の前に、文字の並べ替え順序が依存しているかそれに従います。For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

比較は、単語の並べ替え規則を使用して実行されます。The comparison is performed using word sort rules. 単語、文字列、および序数の並べ替えの詳細については、次を参照してください。System.Globalization.CompareOptionsします。For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both strings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合、残りの文字を含む文字列が大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

序数に基づく比較を使用して、「ファイル」へのパス名を比較します。Compare the path name to "file" using an ordinal comparison. これを行う適切なコードは次のとおりです。The correct code to do this is as follows:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, String, Boolean, CultureInfo)カルチャに依存した比較を実行するときに、メソッドでこのような文字が考慮されません。The Compare(String, String, Boolean, CultureInfo) method does not consider such characters when it performs a culture-sensitive comparison. 次のコードを実行する場合など、 .NET Framework 4.NET Framework 4 「Ani-正しくない」(ソフト ハイフン、または U + 00AD 使用) では、"animal"の大文字と小文字が、不変性を使用して後で、またはカルチャでは、2 つの文字列が等価であることを示します。For example, if the following code is run on the .NET Framework 4.NET Framework 4 or later, a case-insensitive comparison of "animal" with "Ani-mal" (using a soft hyphen, or U+00AD) using the invariant culture indicates that the two strings are equivalent.

[!code-csharpSystem.String.Compare#23] [!code-vbSystem.String.Compare#23][!code-csharpSystem.String.Compare#23] [!code-vbSystem.String.Compare#23] 文字列比較で無視できる文字を認識するように呼び出す、Compare(String, String, CultureInfo, CompareOptions)メソッドと値のいずれかの供給OrdinalまたはOrdinalIgnoreCaseoptionsパラメーター。To recognize ignorable characters in a string comparison, call the Compare(String, String, CultureInfo, CompareOptions) method and supply a value of either Ordinal or OrdinalIgnoreCase for the options parameter.

こちらもご覧ください

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

指定した規則を使用して、指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。Compares two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

public:
 static int Compare(System::String ^ strA, System::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 String String String

比較する最初の文字列。The first string to compare.

strB
String String String String

比較する 2 番目の文字列。The second string to compare.

comparisonType
StringComparison StringComparison StringComparison StringComparison

比較で使用する規則を指定する列挙値の 1 つ。One of the enumeration values that specifies the rules to use in the comparison.

戻り値

2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数。A 32-bit signed integer that indicates the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero 並べ替え順序において strAstrB の前になります。strA precedes strB in the sort order.
0Zero strA は並べ替え順序で、strB と同じ位置にあります。strA is in the same position as strB in the sort order.
0 より大きい値Greater than zero 並べ替え順序において strAstrB の後ろになります。strA follows strB in the sort order.

例外

comparisonTypeStringComparison 値ではありません。comparisonType is not a StringComparison value.

次の例では、3 つのバージョン、文字の"I"。The following example compares three versions of the letter "I". 結果は、カルチャ、ケースが無視されるかどうか、および序数の比較を実行するかどうかの選択肢の影響を受けます。The results are affected by the choice of culture, whether case is ignored, and whether an ordinal comparison is performed.

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

Imports System
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 'Main
    
    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 'Test
End Class 'Sample

'
'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パラメーターは、比較では、現在またはインバリアント カルチャを使用する必要があります、かどうかを優先または、比較対照値の大文字と小文字を無視または word (カルチャ) を使用して、ことを示します。 または、序数 (カルチャに依存しない) の並べ替え規則。The comparisonType parameter indicates whether the comparison should use the current or invariant culture, honor or ignore the case of the comparands, or use word (culture-sensitive) or ordinal (culture-insensitive) sort rules.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both strings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合に残りの文字の文字列は大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

序数に基づく比較を使用して、「ファイル」へのパス名を比較します。Compare the path name to "file" using an ordinal comparison. これを行う適切なコードは次のとおりです。The correct code to do this is as follows:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, String, StringComparison)カルチャに依存した比較を実行するときに、メソッドでこのような文字が考慮されません。The Compare(String, String, StringComparison) method does not consider such characters when it performs a culture-sensitive comparison. 比較で無視できる文字を認識するように、値を与えるOrdinalまたはOrdinalIgnoreCasecomparisonTypeパラメーター。To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

こちらもご覧ください

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

指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを設定できます。Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

public:
 static int Compare(System::String ^ strA, System::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 String String String

比較する最初の文字列。The first string to compare.

strB
String String String String

比較する 2 番目の文字列。The second string to compare.

ignoreCase
Boolean Boolean Boolean Boolean

比較時に大文字と小文字の区別を無視する場合は true。それ以外の場合は falsetrue to ignore case during the comparison; otherwise, false.

戻り値

2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数。A 32-bit signed integer that indicates the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero 並べ替え順序において strAstrB の前になります。strA precedes strB in the sort order.
0Zero strA は並べ替え順序で、strB と同じ位置に出現します。strA occurs in the same position as strB in the sort order.
0 より大きい値Greater than zero 並べ替え順序において strAstrB の後ろになります。strA follows strB in the sort order.

次の例を示している、Compare(String, String, Boolean)メソッドを使用してToUpperまたはToLower文字列を比較するときにします。The following example demonstrates that the Compare(String, String, Boolean) method is equivalent to using ToUpper or ToLower when comparing strings.

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
using System;

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

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

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

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

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

注釈

比較では、現在のカルチャを使用して、個々 の文字のアルファベット順、大文字小文字の規則などのカルチャに固有の情報を取得します。The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. たとえば、カルチャが特定の文字の組み合わせが単一の文字として扱うか、特定の方法では、大文字と小文字を比較することを指定できますまたは文字の前に、文字の並べ替え順序が依存しているかそれに従います。For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

比較は、単語の並べ替え規則を使用して実行されます。The comparison is performed using word sort rules. 単語、文字列、および序数の並べ替えの詳細については、次を参照してください。System.Globalization.CompareOptionsします。For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

警告

文字列を比較するときに呼び出す必要があります、Compare(String, String, StringComparison)メソッドで、明示的にメソッドを使用する文字列比較の種類を指定する必要があります。When comparing strings, you should call the Compare(String, String, StringComparison) method, which requires that you explicitly specify the type of string comparison that the method uses. 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。For more information, see Best Practices for Using Strings.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both strings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合、残りの文字を含む文字列が大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

序数に基づく比較を使用して、「ファイル」へのパス名を比較します。Compare the path name to "file" using an ordinal comparison. これを行う適切なコードは次のとおりです。The correct code to do this is as follows:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, String, Boolean)カルチャに依存した比較を実行するときに、メソッドでこのような文字が考慮されません。The Compare(String, String, Boolean) method does not consider such characters when it performs a culture-sensitive comparison. 次のコードを実行する場合など、.NET Framework 4.NET Framework 4または、後で、"animal"と「Ani-正しくない」(ソフト ハイフン、または U + 00AD 使用) のカルチャ、大文字の比較では 2 つの文字列が等価であることを示します。For example, if the following code is run on the .NET Framework 4.NET Framework 4 or later, a culture-sensitive, case-insensitive comparison of "animal" with "Ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.

[!code-csharpSystem.String.Compare#22] [!code-vbSystem.String.Compare#22][!code-csharpSystem.String.Compare#22] [!code-vbSystem.String.Compare#22] 文字列比較で無視できる文字を認識するように呼び出す、Compare(String, String, StringComparison)メソッドと値のいずれかの供給OrdinalまたはOrdinalIgnoreCasecomparisonTypeパラメーター。To recognize ignorable characters in a string comparison, call the Compare(String, String, StringComparison) method and supply a value of either Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

こちらもご覧ください

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

指定した 2 つの String オブジェクトを比較し、それらの相対位置を並べ替え順序で示す整数を返します。Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

public:
 static int Compare(System::String ^ strA, System::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 String String String

比較する最初の文字列。The first string to compare.

strB
String String String String

比較する 2 番目の文字列。The second string to compare.

戻り値

2 つの比較対照値の構文上の関係を示す 32 ビット符号付き整数。A 32-bit signed integer that indicates the lexical relationship between the two comparands.

[値]Value 条件Condition
0 より小さい値Less than zero 並べ替え順序において strAstrB の前になります。strA precedes strB in the sort order.
0Zero strA は並べ替え順序で、strB と同じ位置に出現します。strA occurs in the same position as strB in the sort order.
0 より大きい値Greater than zero 並べ替え順序において strAstrB の後ろになります。strA follows strB in the sort order.

次の例では、Compare(String, String)文字列の 3 つのセットを比較するメソッド。The following example calls the Compare(String, String) method to compare three sets of strings.

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
using System;

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

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

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

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

      // The previous method call is equivalent to this Compare method, which ignores case.
      Console.WriteLine("The Strings are equal when case is ignored? {0}",
                        String.Compare(stringUpper, stringLower, true) == 0
                                       ? "true" : "false" );
   }
} 
// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true
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クラスは 2 つの文字列を評価する方法を示します、Compareメソッド。In the following example, the ReverseStringComparer class demonstrates how you can evaluate two strings with the Compare method.

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

   }
}

Imports System
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 'Main
   
   
    
    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 'PrintValues
End Class 'SamplesArrayList

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

注釈

比較では、現在のカルチャを使用して、個々 の文字のアルファベット順、大文字小文字の規則などのカルチャに固有の情報を取得します。The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. たとえば、カルチャが特定の文字の組み合わせが単一の文字として扱うか、特定の方法では、大文字と小文字を比較することを指定できますまたは文字の前に、文字の並べ替え順序が依存しているかそれに従います。For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

比較は、単語の並べ替え規則を使用して実行されます。The comparison is performed using word sort rules. 単語、文字列、および序数の並べ替えの詳細については、次を参照してください。System.Globalization.CompareOptionsします。For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

警告

文字列を比較するときに呼び出す必要があります、Compare(String, String, StringComparison)メソッドで、明示的にメソッドを使用する文字列比較の種類を指定する必要があります。When comparing strings, you should call the Compare(String, String, StringComparison) method, which requires that you explicitly specify the type of string comparison that the method uses. 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。For more information, see Best Practices for Using Strings.

比較対象値の 1 つまたは両方を指定できますnullします。One or both comparands can be null. 定義上、任意の文字列を含む空の文字列 ("")、比較に null 参照; より大きい2 つの null 参照が互いに等しくない比較します。By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both strings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合、残りの文字を含む文字列が大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. 戻り値は、最後に実行される比較の結果です。The return value is the result of the last comparison performed.

比較がカルチャに固有の大文字小文字の規則によって影響を受けると、予期しない結果が発生します。Unexpected results can occur when comparisons are affected by culture-specific casing rules. たとえば、トルコ語では次の例では、間違った結果が生成トルコ語でのファイル システムでは"i"の文字の言語的な大文字小文字の規則が使用されないため"file"にします。For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter "i" in "file".

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
static bool IsFileURI(String path)
{
    return (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

序数に基づく比較を使用して、「ファイル」へのパス名を比較します。Compare the path name to "file" using an ordinal comparison. これを行う適切なコードは次のとおりです。The correct code to do this is as follows:

static bool IsFileURI(String^ path)
{
    return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
static bool IsFileURI(String path)
{
    return (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

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。Character sets include ignorable characters. Compare(String, String)カルチャに依存した比較を実行するときに、メソッドでこのような文字が考慮されません。The Compare(String, String) method does not consider such characters when it performs a culture-sensitive comparison. 次のコードを実行する場合など、.NET Framework 4.NET Framework 4または、後で、"animal"と「ani-正しくない」(ソフト ハイフン、または U + 00AD 使用) のカルチャに依存する比較では 2 つの文字列が等価であることを示します。For example, if the following code is run on the .NET Framework 4.NET Framework 4 or later, a culture-sensitive comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.

[!code-csharpSystem.String.Compare#21] [!code-vbSystem.String.Compare#21][!code-csharpSystem.String.Compare#21] [!code-vbSystem.String.Compare#21] 文字列比較で無視できる文字を認識するように呼び出す、Compare(String, String, StringComparison)メソッドと値のいずれかの供給OrdinalまたはOrdinalIgnoreCasecomparisonTypeパラメーター。To recognize ignorable characters in a string comparison, call the Compare(String, String, StringComparison) method and supply a value of either Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

こちらもご覧ください

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

指定した 2 つの String オブジェクトを比較し、2 つの文字列の互いのリレーションシップを並べ替え順序で示す整数を返します。比較時に、指定した比較オプションと、比較に影響を及ぼすカルチャ固有の情報を使用します。Compares two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two strings to each other in the sort order.

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

比較する最初の文字列。The first string to compare.

strB
String String String String

比較する 2 番目の文字列。The second string to compare.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

カルチャ固有の比較情報を提供するカルチャ。The culture that supplies culture-specific comparison information.

options
CompareOptions CompareOptions CompareOptions CompareOptions

比較の実行時に使用するオプション (大文字と小文字の違いや記号を無視するなど)。Options to use when performing the comparison (such as ignoring case or symbols).

戻り値

strAstrB との構文上の関係を示す 32 ビット符号付き整数。次の表を参照してください。A 32-bit signed integer that indicates the lexical relationship between strA and strB, as shown in the following table

[値]Value 条件Condition
0 より小さい値Less than zero 並べ替え順序において strAstrB の前になります。strA precedes strB in the sort order.

0Zero strA は並べ替え順序で、strB と同じ位置に出現します。strA occurs in the same position as strB in the sort order.

0 より大きい値Greater than zero 並べ替え順序において strAstrB の後ろになります。strA follows strB in the sort order.

例外

optionsCompareOptions 値ではありません。options is not a CompareOptions value.

次の例では、次の 3 つの異なる方法で 2 つの文字列を比較します。 EN-US カルチャでは、言語的な比較を使用します。EN-US カルチャの大文字小文字の言語的な比較を使用します。序数に基づく比較を使用してください。The following example compares two strings in three different ways: using linguistic comparison for the en-US culture; using linguistic case-sensitive comparison for the en-US culture; and using an ordinal comparison. 比較の 3 つのメソッドが 3 つの異なる結果を生成する方法を示しています。It illustrates how the three methods of comparison produce three different results.

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 Example
{
   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'.
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パラメーターを個々 の文字のアルファベット順、大文字小文字の規則など、カルチャに固有の情報を取得します。The comparison uses the culture parameter to obtain culture-specific information, such as casing rules and the alphabetical order of individual characters. たとえば、特定のカルチャは、特定の文字の組み合わせを 1 つの文字として扱うことで、特定の方法で大文字と小文字を比較することを指定できますまたは文字の並べ替え順序の文字が依存しているを前または後します。For example, a particular culture could specify that certain combinations of characters be treated as a single character, that uppercase and lowercase characters be compared in a particular way, or that the sort order of a character depends on the characters that precede or follow it.

注意事項

Compare(String, String, CultureInfo, CompareOptions)メソッドが並べ替え操作をアルファベット順に並べ替えに使用する主な設計されています。The Compare(String, String, CultureInfo, CompareOptions) method is designed primarily for use in sorting or alphabetizing operations. また、メソッドの呼び出しの主な目的は、(メソッド呼び出しでは、戻り値が 0 のテスト) の場合は、2 つの文字列が等しいかどうかを判断するときにない使用する必要があります。It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent (that is, when the purpose of the method call is to test for a return value of zero). 2 つの文字列が等しいかどうかを確認するのには、呼び出し、Equalsメソッド。To determine whether two strings are equivalent, call the Equals method.

によってさらに、比較を指定することができます、optionsパラメーターは、1 つ以上のメンバーで構成される、CompareOptions列挙体。The comparison can be further specified by the options parameter, which consists of one or more members of the CompareOptions enumeration. ただし、このメソッドの目的は、カルチャに依存した文字列比較を実行するため、CompareOptions.OrdinalCompareOptions.OrdinalIgnoreCase値は影響ありません。However, because the purpose of this method is to conduct a culture-sensitive string comparison, the CompareOptions.Ordinal and CompareOptions.OrdinalIgnoreCase values have no effect.

比較対象値のいずれかまたは両方を指定できますnullします。Either or both comparands can be null. 定義上、任意の文字列を含むString.Empty、互いに等しくない比較に null 参照より大きく、2 つの null 参照を比較します。By definition, any string, including String.Empty, compares greater than a null reference, and two null references compare equal to each other.

比較では、非等値が検出されるか、両方の文字列を比較したときに終了します。The comparison terminates when an inequality is discovered or both strings have been compared. ただし、2 つの文字列の比較で 1 つの文字列の末尾に等しく、残りの文字があるその他の文字列、場合に、残りの文字の文字列は大きいと見なされます。However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with the remaining characters is considered greater.

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. Compare(String, String, CultureInfo, CompareOptions)カルチャに依存した比較を実行するときに、メソッドでこのような文字が考慮されません。The Compare(String, String, CultureInfo, CompareOptions) method does not consider such characters when it performs a culture-sensitive comparison. 比較で無視できる文字を認識するように、値を与えるOrdinalまたはOrdinalIgnoreCaseoptionsパラメーター。To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

こちらもご覧ください

適用対象