How to split a string into a fixed length string array?

前端 未结 8 1877
别跟我提以往
别跟我提以往 2020-12-21 02:10

I have a long string like this

dim LongString as String = \"123abc456def789ghi\"

And I want to split it into a string array. Each element

8条回答
  •  臣服心动
    2020-12-21 02:25

    I have added some more logic to @jon code. This will work perfectly for the string which has length less than length passed.

     Public Shared Function SplitByLength(ByVal [text] As String, ByVal length As Integer) As String()
    
        Dim stringLength = text.Length
        Dim arrLength As Integer = ([text].Length \ length) - 1 + IIf(([text].Length 
                                                 Mod length) > 0, 1, 0)
        Dim strArray As String() = New String(arrLength) {}
    
        Dim returnString As String = ""
        Dim i As Integer
        Dim remLength As Integer = 0
    
        For i = 0 To strArray.Length - 1
          remLength = stringLength - i * length
          If remLength < length Then
            strArray(i) = [text].Substring((i * length), remLength)
          Else
            strArray(i) = [text].Substring((i * length), length)
          End If
        Next i
    
           Return  strArray
    END FUNCTION
    

提交回复
热议问题