vb6在每第n个空格分隔空格分隔字符串

时间:2013-02-04 20:42:56

标签: vb6 split

我有一个以空格分隔的字符串变量。我想将变量的内容存储到数组中。使用split,我可以将每个以空格分隔的值存储在数组中。如果我可以在每第7个空格分隔字符串变量,我更愿意。例如,文本可以是:

“你好你好你好你好你好你好你好你好喜hi喜hi嗨嘿嘿嘿嘿嘿嘿嘿嘿嘿”

这不是字符串的实际内容,而是更易于阅读的更简单版本。我想在单词改变的地方或每隔7个空格分开。任何帮助将不胜感激。我当前的代码看起来像这样,它在每个空格处分开。

    ReDim StatsArray(ArrInc)
    StatsArray = Split(Stats)

    For i = 0 To UBound(StatsArray())
        If i > UBound(StatsArray()) Then
            ReDim Preserve StatsArray(i + ArrInc)
        End If

     '  MsgBox StatsArray(i) ' When not commented out, this help me check the array
    Next

3 个答案:

答案 0 :(得分:2)

没有任何内置功能可以为您执行此操作。我想到了几个解决方案:(1)进行拆分,然后迭代阵列。在字符串变量中连接七个数组元素。将结果写入新数组。冲洗并重复。 (2)创建一个数组。逐个字符地逐字符号,将每个字符推入变量并跟踪您遇到的空格;到达第七个空格时,向数组中添加一个元素,将变量复制到该数组,然后清除变量。冲洗并重复。

第一个让我感觉快一点,但我对此非常不错。

答案 1 :(得分:0)

如果我理解你要做什么,一串“1234 12345678 123”会分成1234,1234567,8,123。这是正确的吗?

如果是这样,那么您可以使用正则表达式为您进行拆分。

Function Split7(S As String)
   Dim regex As New RegExp
   regex.Pattern = "[^ ]{7}"
   regex.Global = True
   Split7 = Split(regex.Replace(S, "$& "), " ")
End Function

这将在每个不是空格的第7个字符后插入一个空格。然后使用split函数将整个事物放入数组中。

答案 2 :(得分:0)

另一个尝试,虽然我可能会优化ReDim Preserve,以块的形式执行它们:

Option Explicit

Private Function SplitN( _
    ByRef Source As String, _
    ByVal Delim As String, _
    ByVal N As Long) As String()
    'Delim can be multi-character.
    'Always returns at least 1-element result,
    'even if Source = "".
    Dim SearchPos As Long
    Dim PartPos As Long
    Dim DelimPos As Long
    Dim Parts() As String
    Dim DelimCount As Long
    Dim PartsCount As Long

    SearchPos = 1
    PartPos = SearchPos
    Do
        DelimPos = InStr(SearchPos, Source, Delim)
        If DelimPos > 0 Then
            DelimCount = DelimCount + 1
            If DelimCount = N Then
                DelimCount = 0
                ReDim Preserve Parts(PartsCount)
                Parts(PartsCount) = _
                    Mid$(Source, PartPos, DelimPos - PartPos)
                PartsCount = PartsCount + 1
                PartPos = DelimPos + Len(Delim)
            End If
            SearchPos = DelimPos + Len(Delim)
        End If
    Loop While DelimPos > 0
    ReDim Preserve Parts(PartsCount)
    Parts(PartsCount) = Mid$(Source, PartPos)
    SplitN = Parts
End Function

Private Sub Form_Load()
    Dim S As String
    Dim Parts() As String
    Dim P As Long

    S = "hello hello hello hello hello hello hello " _
      & "hi hi hi hi hi hi hi " _
      & "hey hey hey hey hey hey hey"
    Text1.SelStart = 0
    Text1.SelText = S & vbNewLine & vbNewLine
    Parts = SplitN(S, " ", 7)
    Text1.SelText = "Ubound() = " & UBound(Parts) & vbNewLine
    For P = 0 To UBound(Parts)
        Text1.SelText = Parts(P) & vbNewLine
    Next
End Sub