代码之家  ›  专栏  ›  技术社区  ›  CJ7

为早期版本的VB编写自己的Split函数。如何处理一行中的多个分隔符?

  •  0
  • CJ7  · 技术社区  · 14 年前

    字符串“hello | world | today”将生成数组: arr[0] = "hello", arr[1] = "world", arr[2] = "today" 而不是更正确的: arr[0] = "hello", arr[1] = "world", arr[2] = "", arr[3] = "today" . 如何更正代码以生成后一个结果?

         Public Function Split(ByVal sIn As String, Optional sDelim As _
                String, Optional nLimit As Long = -1, Optional bCompare As _
                 VbCompareMethod = vbBinaryCompare) As Variant
              Dim sRead As String, sOut() As String, nC As Integer
              If sDelim = "" Then
                  Split = sIn
              End If
              sRead = ReadUntil(sIn, sDelim, bCompare)
              Do
                  ReDim Preserve sOut(nC)
                  sOut(nC) = sRead
                  nC = nC + 1
                  If nLimit <> -1 And nC >= nLimit Then Exit Do
                  sRead = ReadUntil(sIn, sDelim)
              Loop While sRead <> ""
              ReDim Preserve sOut(nC)
              sOut(nC) = sIn
              Split = sOut
          End Function
    
          Public Function ReadUntil(ByRef sIn As String, _
                sDelim As String, Optional bCompare As VbCompareMethod _
              = vbBinaryCompare) As String
              Dim nPos As String
              nPos = InStr(1, sIn, sDelim, bCompare)
              If nPos > 0 Then
                  ReadUntil = Left(sIn, nPos - 1)
                  sIn = Mid(sIn, nPos + Len(sDelim))
              End If
          End Function
    
    1 回复  |  直到 14 年前
        1
  •  0
  •   Corin    14 年前

    我没有尝试过很多组合,但它似乎起到了作用。我更改了循环的条件,什么值作为数组中的最后一项输入,并在ReadUntil中添加了一个else。

    Public Function Split(ByVal sIn As String, Optional sDelim As _
          String, Optional nLimit As Long = -1, Optional bCompare As _
           VbCompareMethod = vbBinaryCompare) As Variant
        Dim sRead As String, sOut() As String, nC As Integer
        If sDelim = "" Then
            Split = sIn
        End If
        sRead = ReadUntil(sIn, sDelim, bCompare)
        Do
            ReDim Preserve sOut(nC)
            sOut(nC) = sRead
            nC = nC + 1
            If nLimit <> -1 And nC >= nLimit Then Exit Do
            sRead = ReadUntil(sIn, sDelim)
        Loop While sIn <> ""
        ReDim Preserve sOut(nC)
        sOut(nC) = sRead
        Split = sOut
    End Function
    
    Public Function ReadUntil(ByRef sIn As String, _
          sDelim As String, Optional bCompare As VbCompareMethod _
        = vbBinaryCompare) As String
        Dim nPos As String
        nPos = InStr(1, sIn, sDelim, bCompare)
        If nPos > 0 Then
            ReadUntil = Left(sIn, nPos - 1)
            sIn = Mid(sIn, nPos + Len(sDelim))
        Else
            ReadUntil = sIn
            sIn = ""
        End If
    End Function