I have a problem inserting string elements in a string array... For example, I have a three assignment lines:
a = b
b = c
c = e
Then I want to insert these six variables in string[] variables.
I use the following code, but this code inserts only the last assignment variables (c, e).
for (int i = 0; i < S; i++) // S = 3 number of assignment line
{
variables = assigmnent_lines[i].Split('=');
}
3 Answers 3
List<string> this_is_a_list_of_strings = new List<string>();
foreach (string line in assignment_lines)
{
this_is_a_list_of_strings.AddRange(line.Split('='));
}
string[] strArray = this_is_a_list_of_strings.ToArray();
2 Comments
You are wiping out the variables property on each pass. It would be easier to use a collection property:
List<string> variables = new List<string>();
foreach (string sLine in assignment_lines)
{
variables.AddRange(sLine.Split('='));
}
// If you need an array, you can then use variables.ToArray, I believe.
Comments
In each iteration of the for statement, you are restating what variables is. Instead you should create the array as large as it needs to be and then set each index individually:
String[] variables = new String[S * 2];
for (int i = 0; i < S; i++) {
// you should verify there is an = for assuming the split made two parts
String[] parts = assignment_lines[i].Split('=');
variables[i*2] = parts[0];
variables[i*2+1] = parts[1];
}
An easier alternative would be to use List<String> and add strings as you go dynamically.
1 Comment
String[], but as other answers have indicated, List<String> is much easier and in fact I recommend it more. This is just to show it can be done with arrays.