【发布时间】:2016-03-24 03:02:50
【问题描述】:
基本上,我从一个文本文件中读取 50 行,每行的格式有点像这样:
大卫查默斯 34
我已经使用ReadAllLines 读取了文本文件,因此每一行都应该是数组中的不同条目。
我正在尝试从每一行中获取数字并将它们存储到自己的数组中。现在我得到了错误:
索引和长度必须引用字符串中的位置。
static void getResults(string[] Text)
{
// X = lastIndexOf for ' ' (space)
// x will take position of the last space
// Results = substring
// z will be the length of the string
// z = text.Length
// Substring (x+1,z-x+1)
int lines = 50;
string[] Results = new string[lines];
for (int i = 0; i < Text.Length; i++)
{
int x = Text[i].LastIndexOf(' ');
int z = Text[i].Length;
Results[lines] = Text[i].Substring(x + 1, z - x + 1);
}
}
任何帮助将不胜感激!
【问题讨论】:
-
当您收到此错误时,您是否使用了调试器并检查了您的变量?
-
Results[50]将不在数组中 - 大概你想要Results[i] -
您是否意识到您总是在数组中的同一位置写入(行数=50)?并且该位置不存在,因为 NET 中的数组从零开始并以长度结束 - 1(这里最多 49)?
-
不应该是
z - (x + 1)还是z - x - 1 -
我不知道你为什么不使用
string.Split()方法来做到这一点,如果你得到超过50行的话,它会更有效,代码更少......至少@987654328只要文件格式保持不变,@函数仍然可以工作..
标签: c# arrays substring indexof