【发布时间】:2017-08-29 23:10:33
【问题描述】:
我需要解析文本文件中的特定行,其中以特定单词开头,如下图所示:
我只需要解析以“Level”开头的行,只提取“Row”和“Col”的值。 请注意,文本文件将包含 6 组此类数据,其中每组以
开头---------------- 染色体 : # ------------------
请参阅以下示例:Sample
我需要将每个组的行和列保存在一个单独的列表中!!。 有没有办法做到这一点?
我尝试了以下方法:
public List<int[,]> getValuesFromTextFile(String filePath ) {
IEnumerable<string> allLines = Enumerable.Empty<string>();
List<int[,]> path = new List<int[,]>();
int[,] item = new int[2,1];
if (File.Exists(filePath))
{
//Read all content of the files and store it to the list split with new line
allLines = File.ReadLines(filePath);
}
//all Level lines
IEnumerable<string> levelLines = allLines.Where(d => d.StartsWith("Level", StringComparison.CurrentCultureIgnoreCase));
foreach(string line in levelLines)
{
string[] values= line.Split(':');//either space or tab or others as your file contain seperator
for(int i=1; i <values.Length;i++) {
string value = values[i];// skip index 0,it contains label, remaining are point data
if (i == 3) item[1,0] = Int32.Parse(value);
if (i == 5 && item[1,0] != null ) { item[0,0] = Int32.Parse(value);
path.Add(item);
}
}
}
return path;
}
我在行(if (i == 3) item[1,0] = Int32.Parse(value);)收到以下错误:
输入字符串的格式不正确。
当我在这一行设置一个断点时,我看到字符串“value”的值等于 null!!。
当我添加一个断点来查看所有行列表内容时,我得到如下图:
上述方法需要分别解析每组关卡!!。
【问题讨论】:
-
你的错误很明显。
value不包含可以转换为 int 的字符串。设置一个断点,看看它是什么。 -
你能放一个断点并发布你看到的内容吗?
-
所以,你现在知道这个错误是从哪里来的
-
@L.B:我已经更新了我的问题。 . .
-
我建议您改用正则表达式。请参阅 msdn.microsoft.com/en-us/library/… 以这种方式解析文本会更容易。
标签: c# parsing file-io text-parsing string-parsing