String array in C #

I have a problem inserting string elements into an array of strings ... For example, I have three destination strings:

a = b b = c c = e 

Then I want to insert these six variables into the string[] variables.

I use the following code, but this code only inserts the latest destination variables (c, e).

 for (int i = 0; i < S; i++) // S = 3 number of assignment line { variables = assigmnent_lines[i].Split('='); } 
+4
source share
3 answers
 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(); 
+6
source

You destroy the property of variables in 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. 
0
source

At each iteration of the for statement, you confirm what variables . Instead, you should create an array as large as possible, 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]; } 

A simpler alternative would be to use a List<String> and add rows when dynamically moving.

0
source

Source: https://habr.com/ru/post/1387809/


All Articles