Johnny Grimes
Johnny Grimes

Reputation: 411

Copy between variable length arrays c#

So I have a string array called page and a string array called notesSplit which is created using notes.split().

notessplit could have a variable number of newlines however is never over 10 lines.

I'd like to overwrite the contents of "page" from index 20 - 30 leaving blank lines if the index does not exist in notessplit.

Any ideas?

var page = new string[44]; <-- actually this is from a text file
string notes = "blah \n blah \n";    
string[] notesSplit = notes.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

What I have initially come up with is:

for (var i = 0; i < 9; i++) 
{ 
  if (notesSplit[i] != null) 
  { 
    Page[i + 20] = notesSplit[i]; 
  } else { 
    Page[i + 20] = System.Environment.NewLine; 
  } 
}

Upvotes: 1

Views: 167

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82474

Another option, instead of looping over the arrays, is to use Array.Resize method and Array.Copy method:

// Copied your array definiton:
var page = new string[44];
string notes = "blah \n blah \n";
string[] notesSplit = notes.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

// The suggested solution:
if (notesSplit.Length < 10) 
{    
    Array.Resize(ref notesSplit, 10);
}
Array.Copy(notesSplit, 0, page, 20, 10);

Additional information on Array.Copy can be found here on MSDN

Upvotes: 2

VulgarBinary
VulgarBinary

Reputation: 3589

I'm pretty sure this is what you're looking for.

public string[] Replace(string[] page, string[] notes, int start, int length)
{
  for(var i = 0; i + start < page.Length && i < length; i++)
  {
    if(notes != null && notes.Length > (i))
      page[i+start] = notes[i];
    else
      page[i+start] = Enviroment.NewLine;
  }

  return page;
}

Upvotes: 3

Related Questions