字符串数组可以超过 111 吗?

本文关键字:数组 字符串 | 更新日期: 2023-09-27 17:58:36

我正在尝试创建一个数组,该数组将收集目录中所有文件中的所有行,我以为我终于有了它,但是当字符串数组到达条目 111 时,它崩溃并显示 IndexOutOfRangeException

string[] WordList = new string[AdjectiveListLength];
Console.WriteLine("Length .. " + AdjectiveListLength);
Console.WriteLine("String Length .. " + WordList.Length);
int o = 0;
for (int i = 0; i < FileEntries.Length; i++)
{
    WordList = File.ReadAllLines(FileEntries[i]);
    foreach (string s in WordList)
    {
        Console.WriteLine(s + " .. " + i + " .. " + o);
        WordList[o] = s;
        //o += 1;
    }
}

异常指向我在收到错误时注释掉的 int,我一直在尝试获取它几个小时,我终于走到了这一步,我觉得我离终点线有 1 英寸,但我无法弄清楚发生了什么。

字符串数组可以超过 111 吗?

此任务的最佳方法是使用一个List<string>,该可以在事先不知道 FileEntries 数组中每个文件的长度的情况下使用

List<string> WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
    WordList = File.ReadLines(FileEntries[i]).ToList();
    foreach (string s in WordList)
        Console.WriteLine(s + " .. " + i);
    // If you want also the line number then you could just use normal for..loop and C# 6.0 syntax
    for(int o = 0; o < WordList.Count(); o++)
        Console.WriteLine($"File:{i} at line {o} is ..{WordList[o]}");

}

如果您确实想使用数组,则不需要标注数组的尺寸,因为 File.ReadAllLines 已经为您创建了数组。

string[] WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
    WordList = File.ReadAllLines(FileEntries[i]);
    foreach (string s in WordList)
        Console.WriteLine(s + " .. " + i);
}