比较字符串 - ASCII 空格



这样做有什么区别:

Dim strTest As String
If strTest > " " Then
End If

而这个:

Dim strTest As String
If strTest <> "" Then
End If

我认为代码示例 1 正在比较 ASCII 值(SPACE 的 ASCII 代码是 32)。 我已经浏览了MSDN上的字符串部分,但找不到答案。

更新

我也对这里发生的事情感到困惑:

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

>(大于)运算符将按字母顺序或字符代码值顺序(取决于Option Compare设置)进行测试,而<>(不相等)运算符将测试相等性。 只要两个字符串完全不同,那么<>将始终计算为 True . 只要运算符右侧的字符串按字母顺序或按字符代码值位于第一个字符串之后,>的计算结果就会为 true。 因此:

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

但是,在您的问题中,您正在比较空字符串变量(设置为 Nothing )和空字符串。 在这种情况下,比较运算符将 null 变量视为空字符串。 因此,Nothing <> ""的计算结果应为 False,因为运算符的两端都被视为空字符串。 空字符串或 null 字符串应始终被视为排序顺序中的第一个,因此Nothing > "Hello"计算结果应为 False,因为空字符串先于其他所有字符串。 但是,Nothing > ""应该评估为False因为它们都是平等的,因此既不先于另一方,也不在另一方之后。

为了回答最后一个问题,"Test" > " "将测试字母T是在空格之前还是之后。 如果Option Compare设置为 Text ,它将按字母顺序比较它们,并应返回True(这最终取决于您的区域设置的字母排序)。 如果Option Compare设置为 Binary ,它将根据它们的字符代码值比较它们。 如果它们是 ASCII 字符串,则空格字符的值低于字母,如 T,因此它也应返回 True

最新更新