c# - 找不到 "IndexOutOfRangeException"的原因

标签 c# arrays indexoutofrangeexception

<分区>

我遇到了 indexOutOfBounds 异常的奇怪问题。我需要读取数组中每个字符串的第一个字符。

我在第 5 行 (linesRead[i][0]) 中遇到异常。对我来说最奇怪的部分是,当我尝试添加用于调试 Console.WriteLine(linesRead[0][0])/Console.WriteLine(linesRead[linesRead.Length-1][0]) 的行时,它工作得很好。

string[] linesRead = System.IO.File.ReadAllLines(@"test.txt"); //Just a bunch of lines

for (int i = 0; i < linesRead.Length; i++)
{
    if (linesRead[i][0] == '5')
    {
        //Do stuff
    }
}

The text inside of test.txt:
5|f-----g-----c---g-----a---|

6|--c-----------------------|
5|---Aa-f-----g-----c-------|

5|------ccdf-ff-----g-----c-|

6|--------------c-----------|
5|--g-----a------Aa-f-----g-|

5|----c-------------ccdf-f--|

最佳答案

if (linesRead[i][0] == '5') 如果一行为空,将触发此错误。

尝试

if (linesRead[i].StartsWith("5"))

相反。

关于c# - 找不到 "IndexOutOfRangeException"的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57616763/

相关文章:

c# - 从 .NET Windows 服务检测系统待机/ sleep /休眠?

c - 循环不会递增超过 8?

javascript - Lodash 过滤以返回对象而不是长度为 1 的数组

c# - 用于检查数组边界的 If 语句与 Try/Catch 的比较

c# - Unity3d进度条

c# 打开文件,路径以 %userprofile% 开头

c# - C#使用唯一的整数填充数组No Linq或ArrayLists;

C++:数组到指针衰减问题

c# - IndexOutOfRangeException - 假设 0

c++ - 在 C++ 中将 while 循环与 vector 一起使用时出现超出范围异常