【问题标题】:issue looping through each value of a 2D Jagged Array "Index was outside the bounds of the array"循环遍历二维锯齿状数组的每个值的问题“索引超出了数组的范围”
【发布时间】:2015-01-25 00:36:43
【问题描述】:

我从一个文本文件生成一个 2D 锯齿状数组,该数组是段落 > 句子,这个数组的格式正确,我可以在外部指定一个值,例如 [0][0] 等,它会正确显示。

但是,当我尝试在循环中执行此操作时,我在尝试显示“结果 [0] [0]”时得到“索引超出了数组的范围”。

下面是数组生成代码:

string documentPath = @"I:\Project\Test Text.txt";
string content;
string[][] results;

protected void sentenceSplit()
{
    content = Regex.Replace(File.ReadAllText(documentPath), @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
    var paragraphs = content.Split(new char[] { '\n' });
    results = new string[paragraphs.Length][];
    for (int i = 0; i < results.Length; i++)
    {
        results[i] = Regex.Split(paragraphs[i], @"(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s");
    }
}

这是循环代码:

protected void Intersection()
{
    for (int i = 0; i < results.Length; i++)
    {
        for (int s = 0; s < results.Length; s++)
        {
            TextboxSummary.Text += results[i][s];
        } 
    } 
}

我之前没有对 2D 数组做过很多工作,但我觉得这应该可以工作,当它测试时它不会向文本框输出任何内容,即使它应该从 [0][0] 开始,它肯定包含数据,[1][1] 也保存数据,如果它以某种方式跳到那个。

【问题讨论】:

  • 不是results.Length 在你的外循环和results.Length 在你的内循环指的是同一个对象吗? IIRC,Length 将仅返回第一个维度的大小。我想你想在你的内部循环中使用results[i].Length
  • 轰隆隆我们去了,完全错过了,现在它指出我无法取消它,谢谢。
  • 不客气。有时只需要再睁一只眼闭一只眼,尤其是当您在同一段代码上停留了一段时间时。

标签: c# arrays for-loop


【解决方案1】:

正如我在评论中所说,您的代码在您的内部循环中获取了错误的数组长度。您的内部循环应该获取位于外部循环索引处的数组的长度。像这样:

for (int i = 0; i < results.Length; i++)
{
    // Get the length of the array that is at index i
    for (int s = 0; s < results[i].Length; s++)
    {
        TextboxSummary.Text += results[i][s];
    } 
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多