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

前端 未结 8 1872
别跟我提以往
别跟我提以往 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.

提交回复
热议问题