How to split a string with parentheses in a multidimensional array

I have the following line:

"(X,Y,Z),(A,B,C),(R,S,T)" 

I want to split this into a multidimensional array:

 arr[0] = [x,y,z] arr[1] = [a,b,c] arr[2] = [r,s,t] 

so that:

 arr[0][1] = y, arr[0][2] = z, etc. 

I can do this by removing the first and last parsets, splitting into "), (" and then going through this array and making another split. But I feel dirty, unsure, like a stripper (pun intended) in the backalley bar ... is Is there a cleaner way?

Maybe some LINQ to help?

I am using C #.

+8
arrays c #
source share
4 answers
 string data = "(X,Y,Z),(A,B,C),(R,S,T)"; string[][] stringses = data.Trim('(', ')') .Split(new[] {"),("}, StringSplitOptions.RemoveEmptyEntries) .Select(chunk => chunk.Split(',')) .ToArray(); 
+5
source share

You can make a jagged array (as your code shows) from this with line breaking and LINQ quite easily:

 string original = "(X,Y,Z),(A,B,C),(R,S,T)"; string[] groups = original.Trim('(',')') .Split(new[] {"),("}, StringSplitOptions.RemoveEmptyEntries); string[][] results = groups.Select(g => g.Split(',')).ToArray(); 
+3
source share

Regex is your friend. here is a simple piece of code that does this for you.

 var input = @"(X,Y,Z),(A,B,C),(R,S,T)"; var pattern = @"[A-Za-z,]+\b"; List<List<string>> twoDimentionList = new List<List<string>>(); foreach (Match m in Regex.Matches(input, pattern)) { List<string> values = m.Value.Split(',').ToList<string>(); twoDimentionList.Add(values) } 

Hope this helps!

+3
source share

You can get your data with regular expressions.

Reqular expression: (\(([AZ]+)\,?\))+ This will give you x, y, z in groups .. and then just add them to the second dimensional array :)

0
source share

All Articles