0

I'm not very familiar with the way vb handles arrays. But I have a string coming in that looks like:

Foo,4,7,12,,6|Bar,4,2,87,5,7|Fly,4,,87,5,7

and I need to end up with a 2 dimensional array where the 1st dimension is on the pipes and the 2nd on the commas.

2 Answers 2

4
Dim splitThis = "Foo,4,7,12,,6|Bar,4,2,87,5,7|Fly,4,,87,5,7"
Dim splitAtPipe = splitThis.Split("|"c)
Dim result = splitAtPipe.Select(Function(x) x.Split(","c)).ToArray()

The last line is using LINQ to do a transformation on splitAtPipe. For every element in the array, it is selecting a new thing based on that element (the variable x in the lambda), in this case we are taking the element and transforming via .Split() into an string array, which becomes the new element in the result (i.e. whatever we return from that lambda/function becomes the new element). By default it return an IEnumerable so I called ToArray() to make it a two-dimensional array.

P.S. My explanation is probably not entirely accurate, but should be close enough for a basic understanding...

Sign up to request clarification or add additional context in comments.

3 Comments

Brillant! I'll mark as accepted answer as soon as it will let me. If you have a minute could you explain what the final line is doing, I can't quite follow it.
@KirillPolishchuk sure it is. I looked at it in VS
@Casey, I added an explanation of the last line.
1

You will need to use a jagged array: Check that link:

http://msdn.microsoft.com/en-us/library/2s05feca.aspx

Proposed code in (VB.NET):

Imports System.IO

Class Program
    Private Shared Sub Main()

        Dim line As [String] = "Foo,4,7,12,,6|Bar,4,2,87,5,7|Fly,4,,87,5,7"
        Dim rows As [String]() = line.Split("|"C)
        Dim matrix As [String]()() = New [String](rows.Length - 1)() {}

        For i As Integer = 0 To rows.Length - 1
            matrix(i) = rows(i).Split(","C)
        Next

        Console.WriteLine(matrix(0)(0))
    End Sub
End Class

And the code should be something like that (in C#):

using System.IO;
using System;

class Program
{
    static void Main()
    {

        String line = "Foo,4,7,12,,6|Bar,4,2,87,5,7|Fly,4,,87,5,7";
        String[] rows = line.Split('|');
        String[][] matrix = new String[rows.Length][];

        for(int i =0; i<rows.Length; i++) {
            matrix[i] = rows[i].Split(',');
        }

       Console.WriteLine(matrix[0][0]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.