簡體   English   中英

循環遍歷二維鋸齒狀數組的每個值“索引超出數組范圍”

[英]issue looping through each value of a 2D Jagged Array “Index was outside the bounds of the array”

我從文本文件生成2D鋸齒狀數組,該數組是“段落”>“句子”,此數組格式正確,我可以在外部指定諸如[0] [0]等的值,然后它將正確顯示。

但是,當我嘗試在循環中執行此操作時,當嘗試顯示“ results [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]也會以某種方式跳過該數據。

正如我在評論中所述,您的代碼在內部循環中捕獲了錯誤的數組長度。 您的內部循環應獲取位於外部循環索引處的數組長度。 像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM