How to split a string by x amount of characters

后端 未结 4 482

I have a program where a user enters a list of numbers in the form of a string. This list of numbers is always a multiple of 8.

So the list can contain 8, 16, 32, 40

相关标签:
4条回答
  • 2020-12-06 18:21

    This should split the string into an array of 8-character substrings

    Dim orig = "12344321678900987"
    Dim res = Enumerable.Range(0,orig.Length\8).[Select](Function(i) orig.Substring(i*8,8))
    
    0 讨论(0)
  • 2020-12-06 18:32
    Function slice(ByVal s as String) As String()
        Return (From c As String in s).ToArray()
    End Function
    
    0 讨论(0)
  • 2020-12-06 18:36

    You could use a For loop and Substring:

    Dim strings As New List(Of String)
    
    For i As Integer = 0 To Me.txtInput.Text.Length - 1 Step 8
        strings.Add(Me.txtInput.Text.Substring(i, 8))
    Next
    

    To convert the strings list to an array (if you really need one) you can use strings.ToArray().


    Also, you could use regular expressions and LINQ for a fancy one-liner:

    Text.RegularExpressions.Regex.Matches(Me.txtInput.Text, ".{8}").Select(Function(x) x.Value)
    
    0 讨论(0)
  • 2020-12-06 18:47

    To expand on the accepted answer, this will split a string into parts even if the string isn't divisible by the divisor

        Public Function SplitInParts(s As String, partLength As Integer) As IEnumerable(Of String)
            If String.IsNullOrEmpty(s) Then
                Throw New ArgumentNullException("String cannot be null or empty.")
            End If
            If partLength <= 0 Then
                Throw New ArgumentException("Split length has to be positive.")
            End If
            Return Enumerable.Range(0, Math.Ceiling(s.Length / partLength)).Select(Function(i) s.Substring(i * partLength, If(s.Length - (i * partLength) >= partLength, partLength, Math.Abs(s.Length - (i * partLength)))))
        End Function
    
    0 讨论(0)
提交回复
热议问题