我有一个由文本列表组成的文件,如下所示:
ABC Abbey something
ABD Aasdasd
第一个字符串总是长度为3。因此,我想循环遍历文件内容,将前三个字母存储为键,剩余部分作为值。我会移除它们之间的空格,并按以下方式进行子字符串处理以进行存储。键正常工作,但在存储值的行上返回以下错误:ArgumentOutOfRangeException
这是导致问题的确切代码。
line.Substring(4, line.Length)
如果我调用0到line.length之间的subString,它可以正常工作。只要我调用1到line.length之间的subString,我就会收到错误提示。老实说,我不明白,已经花了几个小时了。请帮忙一下。
class Program {
static string line;
static Dictionary<string, string> stations = new Dictionary<string, string>();
static void Main(string[] args) {
var lines = File.ReadLines("C:\\Users\\username\\Desktop\\a.txt");
foreach (var l in lines) {
line = l.Replace("\t", "");
stations.Add(line.Substring(0, 3), line.Substring(4, line.Length));//error caused by this line
}
foreach(KeyValuePair<string, string> item in stations) {
//Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
Console.ReadLine();
}
}
"ABC XYZ".Substring(4);
就是"XYZ"
。 - Alex K.