有没有办法在for循环中使用子字符串?

时间:2019-04-10 00:21:05

标签: c#

我正在尝试创建一个程序,该程序读取文本文件并将每一行转换为字符串数组元素。数组中的每个元素如下所示 “ 5920 BECDBBAADCBACABEBBED”。我需要摆脱4位数字和空格,只保留字母。

使用代码“字符串[0] =字符串[0] .Substring(5);”适用于单个元素,但是一旦将其放入for循环中,就会引发错误。

        string[] canidateAnswers = File.ReadAllLines("C:/Users/Dayton/Desktop/exam.txt");
        canidateAnswers = canidateAnswers.Skip(1).ToArray();

        for (int x = 0; x < canidateAnswers.Length; x++)
        {
            canidateAnswers[x] = canidateAnswers[x].Substring(5);
        }
        Console.WriteLine(canidateAnswers[0]);

        Console.ReadKey();

1 个答案:

答案 0 :(得分:1)

当索引大于输入字符串的长度时,

string.Substring()抛出exception。您的文件中一行的长度少于6个字符,因此当您索引其中一行时,将引发异常。像这样先尝试检查字符串的长度:

.innerHTML
相关问题