How to split a string by the number of characters

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

Thus, the list may contain the numbers 8, 16, 32, 40, 48, etc.

I need to split this line for every 8 characters.

For example, let's say the user entered "1234123445674567"

How can I split it into an array of strings, where (0) is "12341234" and (1) is "45674567"

Note: The size of the array must be equal to the length of the string divided by 8.

Like this:

Dim stringArray(txtInput.Text.Length/8) as String 

Edit: I know I can do this by creating a loop that counts 8 numbers and splits it into an array, but it will be long and take several variables, and I know that there is a more efficient way to do this. I just don't know the syntax.

+8
string
source share
4 answers

This should break 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)) 
+4
source share

You can use a For 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 a list of strings to an array (if you really need one), you can use strings.ToArray() .


Alternatively, you can use regular expressions and LINQ for a fancy single-line interface:

 Text.RegularExpressions.Regex.Matches(Me.txtInput.Text, ".{8}").Select(Function(x) x.Value) 
+4
source share
 Function slice(ByVal s as String) As String() Return (From c As String in s).ToArray() End Function 
0
source share

To expand on the accepted answer, this will split the string into parts, even if the string is not divisible by

  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
source share

All Articles