如何检查`Split()`结果是否有效?

huangapple go评论75阅读模式
英文:

how to check if Split()result is valid?

问题

我有一个名为LastItem的函数,它返回字符串中的最后一个单词。对于具有值的字符串,它运行正常,但对于空白字符串如"",它会失败。

我正在检查Split函数是否返回一个数组。即使对于空白字符串,IsArray()也会返回true。有没有修复的方法。

错误在代码中作为注释提到。

Sub test()

Debug.Print LastItem("a b c")
Debug.Print LastItem("a")
Debug.Print LastItem("") '''' ===>> 对于这个会出错

End Sub

Public Function LastItem(source As String) As String
    
    Dim arr
    arr = Split(source, Space(1))
    
    If IsArray(arr) Then
        LastItem = arr(UBound(arr)) '''' ===>> 对于 LastItem("") 错误是 [Subscript out of range]
    Else
        LastItem = source
    End If
    
End Function
英文:

I have a function LastItem which returns the last word from the string. It works fine for strings with value but for blanks like "" it fails.

I am checking if Split returned an Array. Even for blank string the IsArray() returns true. Is there a way to Fix it.

Errors are mentioned as comment in the code.

Sub test()

Debug.Print LastItem("a b c")
Debug.Print LastItem("a")
Debug.Print LastItem("") '''' ===> Error for this one

End Sub

Public Function LastItem(source As String) As String
    
    Dim arr
    arr = Split(source, Space(1))
    
    If IsArray(arr) Then
        LastItem = arr(UBound(arr)) '''' ===> For LastItem("") error is [Subscript out of range]
    Else
        LastItem = source
    End If
    
End Function  

答案1

得分: 3

检查上限是否大于-1

Public Function LastItem(source As String) As String
        
    Dim arr
    arr = Split(source, Space(1))
    
    '/ 检查上限是否大于-1
    If UBound(arr) > -1 Then
        LastItem = arr(UBound(arr))
    Else
        LastItem = source
    End If
    
End Function
英文:

Check if upper bound is greater than -1


Public Function LastItem(source As String) As String
    
    Dim arr
    arr = Split(source, Space(1))
    
    '/ Check if upper bound is greater than -1
    If UBound(arr) > -1 Then
        LastItem = arr(UBound(arr))
    Else
        LastItem = source
    End If
    
End Function

答案2

得分: 2

Split始终返回一个数组,因此不需要进行IsArray检查。

如果输入是零长度字符串,那么可以尽早退出。

Public Function LastItem(source As String) As String
    If source = vbNullString Then Exit Function
    
    Dim arr
    arr = Split(source, Space(1))

    LastItem = arr(UBound(arr))
End Function
英文:

Split always returns an array so an IsArray check is unnecessary.

How about this? Bail early if the input is a zero-length string.

Public Function LastItem(source As String) As String
    If source = vbNullString Then Exit Function
    
    Dim arr
    arr = Split(source, Space(1))

    LastItem = arr(UBound(arr))
End Function

huangapple
  • 本文由 发表于 2020年1月4日 01:26:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定