Joe

Joe

  • NA
  • 1
  • 0

String.compareTo method

Dec 21 2005 2:41 PM

 

I am a teaching assistant for a Visual Basic class at my high school.  We are using IDE 7.1.3088 and Framework 1.1.4322.  The students will be learning Java2 next year, so the teacher wants to teach the compareTo method to compare strings, similar to the way it is done in Java, instead of using the StrComp function.  During the demonstration, we realised that the String class .compareTo method does not work in the same way as the compareTo method in Java.  I looked up the compareTo method in the API, and found

[quote]
Public Function CompareTo(ByVal strB As String) As Integer

Summary:
Compares this instance with a specified System.String object.

Parameters:
strB: A System.String.

Return Values:
A 32-bit signed integer indicating the lexical relationship between the two comparands. Value Condition Less than zero This instance is less than strB. Zero This instance is equal to strB. Greater than zero This instance is greater than strB. -or- strB is null.
[/quote]

however, the method summary does not explain how the "lexical relationship" is found.

I also looked at a book, Programming Microsoft Visual Basic.Net by Francesco Balena, Microsoft Press, Redmond, Washington, (c) 2004.  On page 207,

[quote]
CompareTo is similar to the StrComp function but doesn't support case-insensitive comparisons; It considers empty strings greater than null references (Nothing).
[/quote]

to test the compareTo method, I created a form with a button, 2 textBoxes, and 6 labels.  The following code is in a click method of the button:

Label1.Text = TextBox1.Text.CompareTo(TextBox2.Text)
Dim letters1() As Char = TextBox1.Text.ToCharArray()
Dim letters2() As Char = TextBox2.Text.ToCharArray()
Label2.Text = StrComp(TextBox1.Text, TextBox2.Text)
Label3.Text = letters1(0).CompareTo(letters2(0))
Label4.Text = TextBox1.Text < TextBox2.Text
Label5.Text = Microsoft.VisualBasic.Strings.AscW(TextBox1.Text.ToCharArray())
Label6.Text = Microsoft.VisualBasic.Strings.AscW(TextBox2.Text.ToCharArray())

TextBox1(word1) TextBox2(word2) Label1(compareTo) Label2(StrComp) Label3(char) Label4(<) Label5(ascw) label6(ascw)
A a 1 -1 -32 True 65 97
a A -1 1 32 False 97 65
A A 0 0 0 False 65 65
a a 0 0 0 False 97 97
A aa -1 -1 -32 True 65 97
Aa aa 1 -1 -32 True 65 97
B b 1 -1 -32 True 66 98
emily Nick -1 1 23 False 101 78

As shown by my test cases. the compareTo method does not always work the same way as the StrComp function.  Can anyone explain to me what I am doing wrong in my use of the compareTo method, or how the compareTo method is supposed to determine the "lexical relationship between the two comparands"?

Thanks for your help.
Joseph Li

*sorry messed up the bbc code


Answers (1)