I will get the input from the user like this - "99211,99212,99213_1,99214,99215_3" and I store it in a string as
string cpt = "99211,99212,99213_1,99214,99215_3";
cptarray = cpt.Split(',');
I got the output as
cptarray[0] = "99211"
cptarray[1] = "99212"
cptarray[2] = "99213_1"
cptarray[3] = "99214"
cptarray[4] = "99215_3"
But I would like the output to be:
cptarray[0][0] = "99211",""
cptarray[1][0] = "99212",""
cptarray[2][0] = "99213","1"
cptarray[3][0] = "99214",""
cptarray[4][0] = "99215","3"
If I need to get the output like above then can I use the 2D array, is it the correct approach?
-
1Maybe you could use a Dictionary<long, int> or Dictionary<string, string>Mate– Mate2016年11月17日 19:14:42 +00:00Commented Nov 17, 2016 at 19:14
-
What you show is not a 2D array, but a jagged array (an array of arrays).John Alexiou– John Alexiou2016年11月17日 21:07:54 +00:00Commented Nov 17, 2016 at 21:07
1 Answer 1
According to the syntax provided:
cptarray[0][0]
...
cptarray[4][0]
you want a jagged array, not 2D one; you can construct this array with a help of Linq:
var cptarray = cpt
.Split(',')
.Select(number => number.Split('_'))
.Select(items => items.Length == 1 ? new string[] {items[0], ""} : items)
.ToArray();
Test
string test = string.Join(Environment.NewLine, cptarray
.Select((line, index) => string.Format("cptarray[{0}] = {1}",
index,
string.Join(", ", line.Select(item => "\"" + item + "\"")))));
Console.Write(test);
Output
cptarray[0] = "99211", ""
cptarray[1] = "99212", ""
cptarray[2] = "99213", "1"
cptarray[3] = "99214", ""
cptarray[4] = "99215", "3"
answered Nov 17, 2016 at 19:22
Dmitrii Bychenko
188k20 gold badges178 silver badges231 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Arun
this line shows syntax error - string test = string.Join(Environment.NewLine, cptarray .Select((line, index) => $"cptarray[{index}] = {string.Join(", ", line.Select(item => "\"" + item + "\""))}"));
Dmitrii Bychenko
@Aruna: do you use C# 6.0?
$"..." is a string interpolation which appears in C# 6.0Dmitrii Bychenko
@Aruna: I've changed string interpolation for string formatting in the
test (see my edit)lang-cs