通过增加变量的字符串时System.IndexOutOfRangeException

时间:2016-10-26 00:03:44

标签: c# string exception char

试着保持简短。所以我有这么久的代码,不断收到System.IndexOutOfRangeException错误,虽然我会从头开始,但它发生在一个循环中,所以我在这里问。代码本身非常简单,问题肯定在这里。

using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                int i = 0;
                for(;;)
                {
                    if(line[i] == 's' && line[i+1] == 'e' && line[i+2] == ':') break;
                    i++;

                }
                i = i + 2;
                line.Substring(i, line.Length - i);
                Console.WriteLine(line);
            }

解释if语句 - 我正在寻找单词"练习:"结束,所以我可以将后面的内容作为新字符串。

知道我为什么会收到这个错误吗?感谢。

编辑:这是我要阅读的示例文本文件:

  

练习:卧推。参与肌肉群胸部,肩部

     

练习:肩部按压。参与肌肉群肩膀,二头肌

     

练习:电缆行。参与肌肉群,二头肌

1 个答案:

答案 0 :(得分:2)

没有必要使用循环来满足您的需求。你可以使用字符串函数来提取数据,你可以使用类似的东西:

String exercise = "Exercise:hello";
var hello = exercise.Substring (exercise.IndexOf (":"));