0

So I have this piece of code:

static void Main(string[] args)
{
    string name = "John; Jill;";
    string[] arrayOfString = new string[6];
    arrayOfString = name.Split(';');

    for(int i = 0; i < arrayOfString.Length; i++)
    {

        if (String.IsNullOrEmpty(arrayOfString[i]))
        {
            arrayOfString[i] = "EMPTY";
        }
        Console.WriteLine(arrayOfString[i].Trim());  
    }
}

If I ran this code, then the result is:

John
Jill
EMPTY

But what I want to do is display it to something like this:

John
Jill
EMPTY
EMPTY
EMPTY
EMPTY

I tried using length as you can see, but it only counts the elements in array that already has a value in it. Can anyone help me with this problem? Thanks in advance.

1 Answer 1

11

The problem is that you're creating an array with 6 elements here:

string[] arrayOfString = new string[6];

... but then reassigning arrayOfString, which means you're completely ignoring the previous value, here:

arrayOfString = name.Split(';');

So after this statement, arrayOfString only has 3 elements, and your original 6-element array is eligible for garbage collection.

If you always want 6 elements, you should copy the results of Split into that existing array:

string[] arrayOfString = new string[6];
string[] split = name.Split(';', 6); // At most 6 strings
Array.Copy(split, 0, arrayOfString, 0, split.Length);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, I see what I did wrong now. Thanks for the help.

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.