.Compare()
The .Compare()
method is a string method that compares the alphabetical order of two specified strings
and returns an integer that represents their relative ranking.
Syntax
String.Compare(string1, string2, ignoreCase);
- The
.Compare()
method is called on theString
class. It takes twostring
type arguments,string1
andstring2
, and compares them alphabetically. ignoreCase
is an optionalboolean
type argument. By default the.Compare()
method is case-sensitive. Passingtrue
as the third argument makes the.Compare()
method case-insensitive.
The .Compare()
method returns an integer
that represents the relative order of string1
and string2
in the alphabet:
-1
ifstring1
comes beforestring2
0
if their position is the same (string1
andstring2
are identical)1
ifstring2
comes beforestring1
Example
In the following example, the .Compare()
method compares "Pizza"
with "pizza"
and "waffle"
. Then the .WriteLine()
method prints the returned integer to the console:
using System;public class Example {public static void Main (string[] args) {string str1 = "Pizza", str2 = "pizza", str3 = "waffle";Console.WriteLine(String.Compare(str1, str2));Console.WriteLine(String.Compare(str1, str3));}}
In the first case, "pizza"
comes before "Pizza"
in alphabetical order, as it is lowercase and the method is case-sensitive. In the second case, "Pizza"
comes before "waffle"
in alphabetical order. This example results in the following output:
1-1
Codebyte Example
In the following runnable example, the .Compare()
method determines the alphabetical order of string1
and string2
, while the letter casing is ignored. Finally, the .WriteLine()
method prints the returned integer to the console.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.