Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Strings - ASCII SPACE

Tags:

vb.net

What is the difference between doing this:

Dim strTest As String
If strTest > " " Then

End If

and this:

Dim strTest As String
If strTest <> "" Then

End If

I think that code sample 1 is comparing ASCII values (the ASCII code of a SPACE is 32). I have looked through the String section on MSDN but I am unable to find an answer.

Update

I am also confused about what happens here:

 Dim strTest As String = "Test"
  If strTest > " " Then

  End If
like image 957
w0051977 Avatar asked Mar 27 '26 02:03

w0051977


1 Answers

The > (greater than) operator will test by alphabetical order or character code value order (depending on the Option Compare setting), whereas the <> (not equal) operator tests for equality. As long as the two strings are different at all, then <> will always evaluate to True. > will evaluate to true as long as the string on the right side of the operator comes after the first string alphabetically, or by character code value. Therefore:

Option Compare Text  ' Compare strings alphabetically

...

Dim x As String = "Hello"
Dim y As String = "World"

If x <> y Then
    ' This block is executed because the strings are different
Else
    ' This block is skipped
End If

If x > y Then
    ' This block is skipped
Else
    ' This block is executed because "Hello" is less than "World" alphabetically
End If

In your question, however, you are comparing a null string variable (set to Nothing) with an empty string. In that case, the comparison operators treat a null variable as an empty string. Therefore, Nothing <> "" should evaluate to False because both sides of the operator are considered empty strings. An empty or null string should always be considered the first in the sort order, so Nothing > "Hello" should evaluate to False because an empty string comes before everything else. But, Nothing > "" should evaluate to False because they are both equal and therefore neither comes before or after the other.

To answer you final question, "Test" > " " will test if the letter T comes before or after a space. If Option Compare is set to Text, it will compare them alphabetically and should return True (this ultimately depends on the alphabetic sorting for your locale). If Option Compare is set to Binary, it will compare them based on their character code values. If they are ASCII strings, a space character has a lower value than a letter, like T, so it, also, should return True.

like image 91
Steven Doggart Avatar answered Mar 30 '26 12:03

Steven Doggart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!