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

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

    This C# code should work:

    public static string[] SplitByLength(string text, int length)
    {
        // According to your comments these checks aren't necessary, but
        // I think they're good practice...
        if (text == null)
        {
            throw new ArgumentNullException("text");
        }
        if (length <= 0)
        {
            throw new ArgumentOutOfRangeException("length");
        }
        if (text.Length % length != 0)
        {
            throw new ArgumentException
                ("Text length is not a multiple of the split length");
        }
        string[] ret = new string[text.Length / length];
        for (int i = 0; i < ret.Length; i++)
        {
            ret[i] = text.Substring(i * length, length);
        }
        return ret;
    }
    

    Reflector converts that to VB as:

    Public Shared Function SplitByLength(ByVal [text] As String, _
                                          ByVal length As Integer) As String()
        ' Argument validation elided
        Dim strArray As String() = New String(([text].Length \ length)  - 1) {}
        Dim i As Integer
        For i = 0 To ret.Length - 1
            strArray(i) = [text].Substring((i * length), length)
        Next i
        Return strArray
    End Function
    

    It's possible that that isn't idiomatic VB, which is why I've included the C# as well.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题