Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a String into Pairs

Tags:

split

vb.net

How would I go on splitting a string into pairs of letter in VB?

for example: abcdefgh

split into: ab cd ef gh

like image 382
K_McCormic Avatar asked Nov 15 '11 15:11

K_McCormic


2 Answers

I'll throw my hat in the ring:

Dim test As String = "abcdefgh"
Dim results As New List(Of String)

For i As Integer = 0 To test.Length - 1 Step 2
  If i + 1 < test.Length Then
    results.Add(test.Substring(i, 2))
  Else
    results.Add(test.Substring(i))
  End If
Next

MessageBox.Show(String.Join(" ", results.ToArray))
like image 53
LarsTech Avatar answered Sep 24 '22 21:09

LarsTech


The following allows for odd length strings. If the string is zero-length, I'm not sure what you'd want to do, you'll want to address that case.

    Dim src As String = "abcdef"
    Dim size As Integer
    If src.Length > 0 Then
        If src.Length Mod 2 = 0 Then
            size = (src.Length / 2) - 1
        Else
            size = ((src.Length + 1) / 2) - 1
        End If
        Dim result(size) As String
        For i = 0 To src.Length - 1 Step 2
            If i = src.Length - 1 Then
                result(i / 2) = src.Substring(i, 1)
            Else
                result(i / 2) = src.Substring(i, 2)
            End If
        Next
    End If
like image 26
minnow Avatar answered Sep 24 '22 21:09

minnow