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

前端 未结 8 1865
别跟我提以往
别跟我提以往 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:46

    Dim LongString As String = "1234567"
    
    Dim LongArray((LongString.Length + 2) \ 3 - 1) As String
    
    For i As Integer = 0 To LongString.Length - 1 Step 3
        LongArray(i \ 3) = IF (i + 3 < LongString.Length, LongString.Substring(i, 3), LongString.Substring(i, LongString.Length - i))           
    Next
    
    For Each s As String In LongArray
        Console.WriteLine(s)
    Next
    

    There are some interesting parts, the use of the \ integer division (that is always rounded down), the fact that in VB.NET you have to tell to DIM the maximum element of the array (so the length of the array is +1) (this is funny only for C# programmers) (and it's solved by the -1 in the dim), the "+ 2" addition (I need to round UP the division by 3, so I simply add 2 to the dividend, I could have used a ternary operator and the modulus, and in the first test I did it), and the use of the ternary operator IF() in getting the substring.

提交回复
热议问题