String不是null,空或空字符串

Tru*_*f42 12 vbscript asp-classic

检查一个字符串是否有一些字符串(长度大于0),即"Null","Nothing","Empty"或" 空字符串 "是最快最简单的方法(在Classic ASP中)

Ekk*_*ner 8

要确保您处理的Variant属于子类型"string",您需要VarType或TypeName函数.要排除零长度字符串,您需要Len().为了防止空间串,你可以抛出一个Trim().

用于说明/试验的代码:

Option Explicit

Function qq(s) : qq = """" & s & """" : End Function

Function toLiteral(x)
  Select Case VarType(x)
    Case vbEmpty
      toLiteral = "<Empty>"
    Case vbNull
      toLiteral = "<Null>"
    Case vbObject
      toLiteral = "<" & TypeName(x) & " object>"
    Case vbString
      toLiteral = qq(x)
    Case Else
      toLiteral = CStr(x)
  End Select
End Function

Function isGoodStr(x)
  isGoodStr = False
  If vbString = VarType(x) Then
     If 0 < Len(x) Then
        isGoodStr = True
     End If
  End If
End Function

Dim x
For Each x In Array("ok", "", " ", 1, 1.1, True, Null, Empty, New RegExp)
    WScript.Echo toLiteral(x), CStr(isGoodStr(x))
Next
Run Code Online (Sandbox Code Playgroud)

输出:

cscript 26107006.vbs
"ok" True
"" False
" " True
1 False
1.1 False
True False
<Null> False
<Empty> False
<IRegExp2 object> False


ror*_*.ap 7

这是一个单行代码,Null通过将值与空字符串连接来避免所有麻烦。它适用于NullEmpty""、 当然还有实际长度的字符串!它唯一不能(也不应该)工作的是Nothing,因为它适用于对象变量,而字符串则不然。

isNullOrEmpty = (Len("" & myString) = 0)
Run Code Online (Sandbox Code Playgroud)


Roc*_*cky 5

你可以尝试这样的事情:

Function nz(valToCheck, valIfNull)
 If IsNull(valToCheck) then
    nz = valIfNull
 Else
    nz = valToCheck
 End if
End function
Run Code Online (Sandbox Code Playgroud)

然后你会像这样使用它:

if nz(var,"") <> "" then
  '--string has something in it
else
  '--string is null or empty
end is
Run Code Online (Sandbox Code Playgroud)


Con*_*eak 3

您可以使用该VarType()函数检查它是否是一个字符串,然后您可以检查该字符串是否不为空。该语句只会传递非空字符串。

If VarType(MyString) = 8 Then
  If MyString <> "" Then 
    'String is Not Null And Not Empty, code goes here

  End If
End If
Run Code Online (Sandbox Code Playgroud)

  • 您不应该使用 And,而应该使用嵌套的 If,因为 VBScript 会计算两个子表达式。对于非字符串 Len(MyString) 是不必要的/低效的,对于对象甚至是致命的。 (3认同)
  • 请在发布之前测试您的代码。"" 和 Trim(" ") 的 VarType 为 8(字符串)。所以你检查 `VarType(MyString) &gt; 1` 的想法是有缺陷的。 (2认同)