K_McCormic
K_McCormic

Reputation: 334

Splitting a String into Pairs

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

for example: abcdefgh

split into: ab cd ef gh

Upvotes: 5

Views: 1429

Answers (3)

Marcus Hansson
Marcus Hansson

Reputation: 816

In C# you would do like this:

Dictionary<String, String> Split(String input)
{
    if (input.Count % 2 == 0)
    {
        Dictionary<string, string> Pairs = new Dictionary( );

        for (int L = 0, R = 1; L < input.Count && R <= input.Count; ++L, ++R)
        {
            Char 
                Left = input[L],
                Right = input[R];

            Pairs.Add(
                Left.ToString(),
                Right.ToString());
        }
    }

    else
    {
        throw new NotEvenException( );
    }

    return Pairs( );
}

void Main()
{
    var Pairs = Split("ABCDEFGH");

    foreach(string Key in Split("ABCDEFGH"))
    {
        Console.Write("{0}{1}\n", Key, Pairs[Key]);
    }
}


/*
 Output:
 AB
 CD
 EF
 GH

 */

Now, I know what you think: This isn't what I want! But I say: It is actually, at least partly.

Since I presume you're working in VB.net, the basic structure of what you want performed is outlined in the short snippet above.

For example: The method Count (of the object String) exists in both C# and in VB.

Hope it helps a bit at least!

Upvotes: 2

LarsTech
LarsTech

Reputation: 81610

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))

Upvotes: 8

minnow
minnow

Reputation: 1101

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

Upvotes: 3

Related Questions