C#中的字符串数组

我在字符串数组中插入字符串元素时遇到问题…例如,我有三个赋值行:

a = b b = c c = e 

然后我想在string[]变量中插入这六个变量。

我使用以下代码,但此代码仅插入最后一个赋值变量(c,e)。

 for (int i = 0; i < S; i++) // S = 3 number of assignment line { variables = assigmnent_lines[i].Split('='); } 

 List this_is_a_list_of_strings = new List(); foreach (string line in assignment_lines) { this_is_a_list_of_strings.AddRange(line.Split('=')); } string[] strArray = this_is_a_list_of_strings.ToArray(); 

您正在消除每次传递的变量属性。 使用集合属性会更容易:

 List variables = new List(); foreach (string sLine in assignment_lines) { variables.AddRange(sLine.Split('=')); } // If you need an array, you can then use variables.ToArray, I believe. 

在for语句的每次迭代中,您都在重述variables 。 相反,您应该根据需要创建尽可能大的数组,然后单独设置每个索引:

 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]; } 

更简单的替代方法是使用List并动态添加字符串。