String.Compare Method (String, String)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Updated: January 2011

Performs a culture-sensitive comparison of two specified String objects and returns an integer that indicates their relationship to one another in the sort order.

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

Syntax

'Declaration
Public Shared Function Compare ( _
    strA As String, _
    strB As String _
) As Integer
public static int Compare(
    string strA,
    string strB
)

Parameters

Return Value

Type: System.Int32
A 32-bit signed integer indicating the lexical relationship between the two comparands.

Value

Condition

Less than zero

strA is less than strB.

Zero

strA equals strB.

Greater than zero

strA is greater than strB.

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.

Caution noteCaution:

The Compare(String, String) 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 is performed using word sort rules. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

Caution noteCaution:

When comparing strings, you should call the Compare method, which requires that you explicitly specify the type of string comparison that the method uses.

One or both comparands can be nulla null reference (Nothing in Visual Basic). 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".

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

Examples

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

Imports System.Collections.Generic
Imports System.Text

Public Class Example
   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim myAL As New List(Of String)
      ' 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 List.
      outputBlock.Text += String.Format("Count: {0}", myAL.Count) & vbCrLf
      PrintValues(outputBlock, "Unsorted", myAL)
      myAL.Sort()
      PrintValues(outputBlock, "Sorted", myAL)
      Dim comp As New ReverseStringComparer
      myAL.Sort(comp)
      PrintValues(outputBlock, "Reverse", myAL)
   End Sub 

   Public Shared Sub PrintValues(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal title As String, _
                                 ByVal myList As IEnumerable(Of String))
      outputBlock.Text += String.Format("{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)
      outputBlock.Text &= sb.ToString() & vbCrLf
   End Sub
End Class 'SamplesArrayList

Public Class ReverseStringComparer
   Implements IComparer(Of String)

   Function Compare(ByVal x As String, ByVal y As String) As Integer _
            Implements IComparer(Of String).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
End Class 
using System;
using System.Text;
using System.Collections.Generic;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Creates and initializes a new generic List.
      List<string> myAL = new List<string>();
      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.
      outputBlock.Text += String.Format("Count: {0}", myAL.Count) + "\n";

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

   public static void PrintValues(System.Windows.Controls.TextBlock outputBlock, string title, IEnumerable<string> myList)
   {
      outputBlock.Text += String.Format("{0,10}: ", title);
      StringBuilder sb = new StringBuilder();
      foreach (string s in myList)
      {
         sb.AppendFormat("{0}, ", s);
      }
      sb.Remove(sb.Length - 2, 2);
      outputBlock.Text += sb + "\n";
   }
}
public class ReverseStringComparer : IComparer<string>
{
   public int Compare(string x, string 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);

   }
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Change History

Date

History

Reason

January 2011

Added the recommendation to use an overload that has a StringComparison parameter.

Information enhancement.