String.Compare. In VB.NET, 2 Strings can be compared. With Compare, CompareOrdinal, and CompareTo, we can determine whether one String is ordered before another String.
Function info. Compare is used to implement sorting routines. Compare returns just three values: -1, 0 and 1. This number indicates the relation of the two strings being compared.
Example. First we declare two String local variables. Next we call the Shared String.Compare function. It returns -1—this means that String a is smaller than, or comes before, String b.
Next The result of 1 indicates that String "b" is larger than String a. And 0 means the two Strings are equal.
Note CompareOrdinal treats each character as an ordinal value. This means Chars are treated by their numeric value.
Note 2 With CompareTo, we use String instances to perform the comparison. The results are the same as for String.Compare.
Module Module1
Sub Main()
Dim a As String = "a"
Dim b As String = "b"
Dim c As Integer = 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)
c = "x".CompareTo("x")
Console.WriteLine(c)
End Sub
End Module-1
1
-1
1
0
Discussion. In a sort, each String must be compared to other Strings. With Compare and CompareTo, an Enum of StringComparison type can be specified as an argument.
And Internally, those methods will use a Compare method based on the Enum argument.
Summary. With these methods, if the first String is ordered first, we receive the value -1. If the Strings are equal, we receive 0. And we receive 1 if the second String is first.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 30, 2023 (edit link).