C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
String Compare method results:
String A: First alphabetically
String B: Second alphabetically
Compare(A, B): -1
Compare(B, A): 1
Compare(A, A): 0
Compare(B, B): 0
Here: The program shows 3 comparison methods. The Compare and CompareOrdinal methods are static, while CompareTo is an instance method.
CompareToNote: If the first string is bigger, the result is 1. If the first string is smaller, the result is -1.
And: If both strings are equal, the result is 0. The number essentially indicates how much "larger" the first string is.
C# program that uses Compare
using System;
class Program
{
static void Main()
{
string a = "a";
string b = "b";
int c = string.Compare(a, b);
Console.WriteLine(c);
c = string.CompareOrdinal(b, a);
Console.WriteLine(c);
c = a.CompareTo(b);
Console.WriteLine(c);
c = b.CompareTo(a);
Console.WriteLine(c);
}
}
Output
-1 (This means a is smaller than b)
1 (This means b is smaller than a)
-1
1
Tip: You can specify those cultures in the method call as a parameter to accomplish this goal.
Note: Compare methods are not needed to check string equality. You can use the Equals method, or the == operator, for equality.
String EqualsTip: This option is useful in many programs, such as those that deal with the Windows file system where file case is not important.