【问题标题】:Copy between variable length arrays c#在可变长度数组c#之间复制
【发布时间】:2015-05-14 05:46:12
【问题描述】:

所以我有一个名为 page 的字符串数组和一个名为 notesSplit 的字符串数组,它是使用 notes.split() 创建的。

notessplit 可以有可变数量的换行符,但永远不会超过 10 行。

如果 notessplit 中不存在索引,我想覆盖索引 20 - 30 中“页面”的内容,留下空白行。

有什么想法吗?

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);

我最初想出的是:

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

【问题讨论】:

  • 请解释清楚,显示示例输入和所需输出
  • “索引不存在”是什么意思?你的意思是它超出了数组的范围吗?还是没有内容?
  • Merging two arrays in .Net 的可能重复项
  • @ZoharPeled 你认为他为什么要合并数组?
  • “如果索引在 notessplit 中不存在,我想覆盖索引 20 - 30 中“页面”的内容,留下空白行。” 在我看来将 notesSplit 数组合并到 notesArray

标签: c# arrays


【解决方案1】:

我很确定这就是你要找的东西。

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

【讨论】:

  • 谢谢,我想出了这个,但你的更好。 for (var i = 0; i
  • 在此示例中,您可以调用:Replace(page, notesSplit, 20, 8); 给出您在评论中发布的示例。
  • 我修改了解决方案以使用您的示例,其中notesSplit[i] 而不是i+start
  • @VulgarBinary pagestring[],您可以使用Length 属性代替Count() 扩展方法。
  • @YuvalItzchakov - IEnum 扩展在可用时占长度。 :-) O(1) on Array verse O(n) on a true enumerable。如果它能让你更快乐,我可以改变它,但它不会影响性能,输入长度只需少 1 个字符。
【解决方案2】:

另一种选择,而不是遍历数组, 就是使用Array.Resize方法和Array.Copy方法:

// 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);

更多关于Array.Copy的信息可以在here on MSDN找到

【讨论】:

  • @VulgarBinary:这是代码可读性的确切定义……至于性能我没有测试,但结果应该是一样的。
  • 我的语法相当于Replace(page, notesSplit, 20, 10) 你的要长得多;-) 这就是我把它做成自己的方法的原因。
  • 无论如何,两者都是有效的,都应该工作。只是让你刮目相看:-)
  • @VulgarBinary:我同意。它们都是有效的。
  • 任何时候 :-) 当涉及到任何值得链接的问题时,我通常会在任何值得阅读的答案或问题本身中做任何事情。如果其他人对语法、概念或技术不确定,可以帮助他们绊倒 Q。乐于助人!
猜你喜欢
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 2014-06-17
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
相关资源
最近更新 更多