5

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

6
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();
Sign up to request clarification or add additional context in comments.

2 Comments

'chars' is a deceptive name for a list of strings :)
Thank you jb., I edited my original answer. I don't want to confuse people interested to learn programming :)
0

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

0

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

This works using simple 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.