AxiServices
asked on
How to Split a string with multiple delimiters into a multidimensional array in C#
I have a string with multiple delimters
e.g. string myList = A:1,B:2,C:3,D:4;
And I would like to parse it into a multi-dimensional array like:
string[,] myArray = myList.Split(new char[] {":",","} );
How can I do this without splitting the string twice or doing some for loop, etc. Is there a way to do it in 1 or 2 lines?
By the way, using C# 2.0
e.g. string myList = A:1,B:2,C:3,D:4;
And I would like to parse it into a multi-dimensional array like:
string[,] myArray = myList.Split(new char[] {":",","} );
How can I do this without splitting the string twice or doing some for loop, etc. Is there a way to do it in 1 or 2 lines?
By the way, using C# 2.0
Or actually, that should be
myArray(0)(0) = "A"
myArray(0)(1) = "1"
myArray(1)(0) = "B"
myArray(1)(1) = "1"
myArray(0)(0) = "A"
myArray(0)(1) = "1"
myArray(1)(0) = "B"
myArray(1)(1) = "1"
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for the responses so far. I tried the following using a hashtable instead. However, I was hoping to use an array. I have simliar code to the above, but I have several other places where I will need to do the same and am looking for something a little less verbose.
Current code (changed from string array to hashtable):
String s = "A:1,B:2,C:3,D:4";
String[] s1 = s.Split(',');
Hashtable hash = new Hashtable();
foreach(string country in CountryRates)
hash.Add(s.Split(':')[0], s.Split(':')[0])
Current code (changed from string array to hashtable):
String s = "A:1,B:2,C:3,D:4";
String[] s1 = s.Split(',');
Hashtable hash = new Hashtable();
foreach(string country in CountryRates)
hash.Add(s.Split(':')[0], s.Split(':')[0])
ASKER
Correction to previous post:
String s = "A:1,B:2,C:3,D:4";
String[] s1 = s.Split(',');
Hashtable hash = new Hashtable();
foreach(string str in s)
hash.Add(str.Split(':')[0] , str.Split(':')[0])
String s = "A:1,B:2,C:3,D:4";
String[] s1 = s.Split(',');
Hashtable hash = new Hashtable();
foreach(string str in s)
hash.Add(str.Split(':')[0]
ASKER
Has anyone tried RegEx.split and tried to convert a string into a string[,] ? Is that even possible?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks. I ended up using a hashtable so that I can easily maneuver around the object and its argument. I was hoping to simplify the code a bit. Thanks for the help, though!
What are the results you are looking for, something like this?
myArray(0) = "A"
myArray(0)(0) = "1"
myArray(1) = "B"
myArray(1)(0) = "2"