Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by x amount of characters

Tags:

string

vb.net

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, 48, etc. numbers.

I need to split that string into every 8 characters.

For example, say the user entered "1234123445674567"

How can I split it into a string array where (0) is "12341234" and (1) is "45674567"

Note: The size of the array has to 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 could do this by making a loop that counts 8 numbers and splits it into an array but that would be lengthy and take a few variables and I know there's a more efficient way to do it. I just don't know the syntax.

like image 938
Mark Kramer Avatar asked Jan 08 '12 00:01

Mark Kramer


2 Answers

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))
like image 108
Sergey Kalinichenko Avatar answered Oct 20 '22 11:10

Sergey Kalinichenko


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)
like image 26
Ry- Avatar answered Oct 20 '22 11:10

Ry-