String.Compare Method

Definition

Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

Overloads

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

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, Int32, String, Int32, Int32, Boolean, CultureInfo)

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)

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, Boolean)

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)

Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

Compare(String, String, CultureInfo, CompareOptions)

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(String, String, Boolean, CultureInfo)

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)

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)

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)

Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

Remarks

All overloads of the Compare method return a 32-bit signed integer indicating the lexical relationship between the two comparands.

Value Condition
Less than zero The first substring precedes the second substring in the sort order.
Zero The substrings occur in the same position in the sort order, or length is zero.
Greater than zero The first substring follows the second substring in the sort order.

Warning

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, CultureInfo, CompareOptions)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

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.

C#
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
C#
public static int Compare (string strA, int indexA, string strB, int indexB, int length, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);

Parameters

strA
String

The first string to use in the comparison.

indexA
Int32

The starting position of the substring within strA.

strB
String

The second string to use in the comparison.

indexB
Int32

The starting position of the substring within strB.

length
Int32

The maximum number of characters in the substrings to compare.

culture
CultureInfo

An object that supplies culture-specific comparison information. If culture is null, the current culture is used.

options
CompareOptions

Options to use when performing the comparison (such as ignoring case or symbols).

Returns

An integer that indicates the lexical relationship between the two substrings, as shown in the following table.

Value Condition
Less than zero The substring in strA precedes the substring in strB in the sort order.
Zero The substrings occur in the same position in the sort order, or length is zero.
Greater than zero The substring in strA follows the substring in strB in the sort order.

Exceptions

options is not a CompareOptions value.

indexA is greater than strA.Length.

-or-

indexB is greater than strB.Length.

-or-

indexA, indexB, or length is negative.

-or-

Either strA or strB is null, and length is greater than zero.

Examples

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.

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

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

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

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

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

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

Remarks

The substrings to compare start in strA at position indexA and in strB at position indexB. The length of the first substring is the length of strA minus indexA. The length of the second substring is the length of strB minus indexB.

The number of characters to compare is the lesser of the lengths of the two substrings, and length. The indexA, indexB, and length parameters must be nonnegative.

The comparison uses the culture parameter to obtain culture-specific information, such as casing rules and the alphabetical order of individual characters. 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.

Caution

The Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method is designed primarily for use in sorting or alphabetizing operations. 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). To determine whether two strings are equivalent, call the Equals method.

One or both of strA and strB can be 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 can be further specified by the options parameter, which consists of one or more members of the System.Globalization.CompareOptions enumeration. 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. 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.

Notes to Callers

Character sets include ignorable characters. The Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

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

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

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.

C#
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo? culture);
C#
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture);

Parameters

strA
String

The first string to use in the comparison.

indexA
Int32

The position of the substring within strA.

strB
String

The second string to use in the comparison.

indexB
Int32

The position of the substring within strB.

length
Int32

The maximum number of characters in the substrings to compare.

ignoreCase
Boolean

true to ignore case during the comparison; otherwise, false.

culture
CultureInfo

An object that supplies culture-specific comparison information. If culture is null, the current culture is used.

Returns

An integer that indicates the lexical relationship between the two comparands.

Value Condition
Less than zero The substring in strA precedes the substring in strB in the sort order.
Zero The substrings occur in the same position in the sort order, or length is zero.
Greater than zero The substring in strA follows the substring in strB in the sort order.

Exceptions

indexA is greater than strA.Length.

-or-

indexB is greater than strB.Length.

-or-

indexA, indexB, or length is negative.

-or-

Either strA or strB is null, and length is greater than zero.

Examples

The following example compares two substrings using different cultures and ignoring the case of the substrings. The choice of culture affects how the letter "I" is compared.

C#
// Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using System;
using System.Globalization;

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

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

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

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

Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*/

Remarks

The substrings to compare start in strA at indexA, and in strB at indexB. Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero, not position one. The length of the first substring is equal to the length of strA minus indexA plus one. The length of the second substring is equal to the length of strB minus indexB plus one.

The number of characters to compare is the lesser of the lengths of the two substrings, and length. The indexA, indexB, and length parameters must be nonnegative.

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. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

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

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

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

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

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

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

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

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Compares substrings of two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

C#
public static int Compare (string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
C#
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, StringComparison comparisonType);

Parameters

strA
String

The first string to use in the comparison.

indexA
Int32

The position of the substring within strA.

strB
String

The second string to use in the comparison.

indexB
Int32

The position of the substring within strB.

length
Int32

The maximum number of characters in the substrings to compare.

comparisonType
StringComparison

One of the enumeration values that specifies the rules to use in the comparison.

Returns

A 32-bit signed integer that indicates the lexical relationship between the two comparands.

Value Condition
Less than zero The substring in strA precedes the substring in strB in the sort order.
Zero The substrings occur in the same position in the sort order, or the length parameter is zero.
Greater than zero The substring in strA follows the substring in strB in the sort order.

Exceptions

indexA is greater than strA.Length.

-or-

indexB is greater than strB.Length.

-or-

indexA, indexB, or length is negative.

-or-

Either indexA or indexB is null, and length is greater than zero.

comparisonType is not a StringComparison value.

Examples

The following example compares two substrings.

C#
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'.
*/

Remarks

The substrings to compare start in strA at indexA and in strB at indexB. Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero, not position one. The length of the first substring is equal to the length of strA minus indexA plus one. The length of the second substring is equal to the length of strB minus indexB plus one.

The number of characters to compare is the lesser of the lengths of the two substrings, and length. The indexA, indexB, and length parameters must be nonnegative.

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.

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

The comparison terminates when an inequality is discovered or both substrings have been compared. 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. 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".

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

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

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, Int32, String, Int32, Int32, StringComparison) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

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.

C#
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase);
C#
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);

Parameters

strA
String

The first string to use in the comparison.

indexA
Int32

The position of the substring within strA.

strB
String

The second string to use in the comparison.

indexB
Int32

The position of the substring within strB.

length
Int32

The maximum number of characters in the substrings to compare.

ignoreCase
Boolean

true to ignore case during the comparison; otherwise, false.

Returns

A 32-bit signed integer that indicates the lexical relationship between the two comparands.

Value Condition
Less than zero The substring in strA precedes the substring in strB in the sort order.
Zero The substrings occur in the same position in the sort order, or length is zero.
Greater than zero The substring in strA follows the substring in strB in the sort order.

Exceptions

indexA is greater than strA.Length.

-or-

indexB is greater than strB.Length.

-or-

indexA, indexB, or length is negative.

-or-

Either indexA or indexB is null, and length is greater than zero.

Examples

The following example performs two comparisons of two substrings that only differ in case. The first comparison ignores case and the second comparison considers case.

C#
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'.
*/

Remarks

The substrings to compare start in strA at indexA, and in strB at indexB. Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero. The length of the first substring is equal to the length of strA minus indexA plus one. The length of the second substring is equal to the length of strB minus indexB plus one.

The number of characters to compare is the lesser of the lengths of the two substrings, and length. 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. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

Warning

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.

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

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

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

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

The path name needs to be compared in an invariant manner. The correct code to do this is as follows.

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, Int32, String, Int32, Int32, Boolean) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

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

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

C#
public static int Compare (string strA, int indexA, string strB, int indexB, int length);
C#
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length);

Parameters

strA
String

The first string to use in the comparison.

indexA
Int32

The position of the substring within strA.

strB
String

The second string to use in the comparison.

indexB
Int32

The position of the substring within strB.

length
Int32

The maximum number of characters in the substrings to compare.

Returns

A 32-bit signed integer indicating the lexical relationship between the two comparands.

Value Condition
Less than zero The substring in strA precedes the substring in strB in the sort order.
Zero The substrings occur in the same position in the sort order, or length is zero.
Greater than zero The substring in strA follows the substring in strB in the sort order.

Exceptions

indexA is greater than strA.Length.

-or-

indexB is greater than strB.Length.

-or-

indexA, indexB, or length is negative.

-or-

Either indexA or indexB is null, and length is greater than zero.

Examples

The following example compares two substrings.

C#
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'.
*/

Remarks

The substrings to compare start in strA at indexA and in strB at indexB. Both indexA and indexB are zero-based; that is, the first character in strA and strB is at position zero. The length of the first substring is equal to the length of strA minus indexA plus one. The length of the second substring is equal to the length of strB minus indexB plus one.

The number of characters to compare is the lesser of the lengths of the two substrings, and length. 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. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

Warning

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.

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

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

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

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

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

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, Int32, String, Int32, Int32) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. 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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Compare(String, String, CultureInfo, CompareOptions)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

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.

C#
public static int Compare (string? strA, string? strB, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
C#
public static int Compare (string strA, string strB, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);

Parameters

strA
String

The first string to compare.

strB
String

The second string to compare.

culture
CultureInfo

The culture that supplies culture-specific comparison information. If culture is null, the current culture is used.

options
CompareOptions

Options to use when performing the comparison (such as ignoring case or symbols).

Returns

A 32-bit signed integer that indicates the lexical relationship between strA and strB, as shown in the following table

Value Condition
Less than zero strA precedes strB in the sort order.
Zero strA occurs in the same position as strB in the sort order.
Greater than zero strA follows strB in the sort order.

Exceptions

options is not a CompareOptions value.

Examples

The following example compares two strings in three different ways: Use linguistic comparison for the en-US culture; using linguistic case-sensitive comparison for the en-US culture; and using an ordinal comparison. It illustrates how the three methods of comparison produce three different results.

C#
using System;
using System.Globalization;

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

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

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

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

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

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

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

Remarks

The comparison uses the culture parameter to obtain culture-specific information, such as casing rules and the alphabetical order of individual characters. 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.

Caution

The Compare(String, String, CultureInfo, CompareOptions) method is designed primarily for use in sorting or alphabetizing operations. 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). To determine whether two strings are equivalent, call the Equals method.

The comparison can be further specified by the options parameter, which consists of one or more members of the CompareOptions enumeration. 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.

Either or both comparands can be 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. 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.

Notes to Callers

Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. The Compare(String, String, CultureInfo, CompareOptions) method does not consider such characters when it performs a culture-sensitive comparison. To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Compare(String, String, Boolean, CultureInfo)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

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.

C#
public static int Compare (string? strA, string? strB, bool ignoreCase, System.Globalization.CultureInfo? culture);
C#
public static int Compare (string strA, string strB, bool ignoreCase, System.Globalization.CultureInfo culture);

Parameters

strA
String

The first string to compare.

strB
String

The second string to compare.

ignoreCase
Boolean

true to ignore case during the comparison; otherwise, false.

culture
CultureInfo

An object that supplies culture-specific comparison information. If culture is null, the current culture is used.

Returns

A 32-bit signed integer that indicates the lexical relationship between the two comparands.

Value Condition
Less than zero strA precedes strB in the sort order.
Zero strA occurs in the same position as strB in the sort order.
Greater than zero strA follows strB in the sort order.

Examples

The following example demonstrates how culture can affect a comparison. In Czech - Czech Republic culture, "ch" is a single character that is greater than "d". However, in English - United States culture, "ch" consists of two characters, and "c" is less than "d".

C#
public static void Main()
{
    String str1 = "change";
    String str2 = "dollar";
    String relation;

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

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

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

/*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*/

Remarks

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. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

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

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

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

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

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

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, String, Boolean, CultureInfo) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .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.

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

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

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

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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Compare(String, String, StringComparison)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Compares two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

C#
public static int Compare (string strA, string strB, StringComparison comparisonType);
C#
public static int Compare (string? strA, string? strB, StringComparison comparisonType);

Parameters

strA
String

The first string to compare.

strB
String

The second string to compare.

comparisonType
StringComparison

One of the enumeration values that specifies the rules to use in the comparison.

Returns

A 32-bit signed integer that indicates the lexical relationship between the two comparands.

Value Condition
Less than zero strA precedes strB in the sort order.
Zero strA is in the same position as strB in the sort order.
Greater than zero strA follows strB in the sort order.

Exceptions

comparisonType is not a StringComparison value.

Examples

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.

C#
// 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)

*/

Remarks

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.

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

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

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

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

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

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, String, StringComparison) method does not consider such characters when it performs a culture-sensitive comparison. To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the comparisonType parameter.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Compare(String, String, Boolean)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

C#
public static int Compare (string strA, string strB, bool ignoreCase);
C#
public static int Compare (string? strA, string? strB, bool ignoreCase);

Parameters

strA
String

The first string to compare.

strB
String

The second string to compare.

ignoreCase
Boolean

true to ignore case during the comparison; otherwise, false.

Returns

A 32-bit signed integer that indicates the lexical relationship between the two comparands.

Value Condition
Less than zero strA precedes strB in the sort order.
Zero strA occurs in the same position as strB in the sort order.
Greater than zero strA follows strB in the sort order.

Examples

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

C#
// 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

Remarks

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

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

Warning

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.

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

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

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

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

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

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, String, Boolean) method does not consider such characters when it performs a culture-sensitive comparison. For example, 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.

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

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

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

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Compare(String, String)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

C#
public static int Compare (string strA, string strB);
C#
public static int Compare (string? strA, string? strB);

Parameters

strA
String

The first string to compare.

strB
String

The second string to compare.

Returns

A 32-bit signed integer that indicates the lexical relationship between the two comparands.

Value Condition
Less than zero strA precedes strB in the sort order.
Zero strA occurs in the same position as strB in the sort order.
Greater than zero strA follows strB in the sort order.

Examples

The following example calls the Compare(String, String) method to compare three sets of strings.

C#
// 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

In the following example, the ReverseStringComparer class demonstrates how you can evaluate two strings with the Compare method.

C#
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);
    }
}

Remarks

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

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

Warning

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.

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

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

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

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

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

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

Notes to Callers

Character sets include ignorable characters. The Compare(String, String) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .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.

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

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

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

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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0