【发布时间】:2009-01-15 23:05:51
【问题描述】:
我正在尝试找出解析此逗号分隔文本文件的最佳方法。摘录如下:
bldgA, fred, lunch
bldgA, sally, supper
bldgB, bob, parking lot
bldgB, frank, rooftop
...
我要做的是阅读“bldgA”,然后我想要这个人(第二列),例如“fred”。但我不想解析寻找“fred”的文件,因为下一次可能不会出现 fred,而 bldgA 总是会出现。我想阅读文本文件,看到我在 bldgA 上,然后阅读我列表中的下一项,即 fred。之后我想测试它是否是 fred、sally 等并打印出第三列。我知道这可能使用数据库更容易,但对于一个小文本文件来说似乎有点开销,所以我可以命名列。在我使用 Access 或其他小工具之前,我想我会尝试 Stack Overflow。这是我所拥有的:
string BuildingFile = Server.MapPath("buildings.txt");
StreamReader FileStreamReader;
FileStreamReader = File.OpenText(BuildingFile);
while (FileStreamReader.Peek() != -1)
{
string[] words;
words = FileStreamReader.ReadLine().Split(',');
foreach (string word in words)
{
if (word == "bldgA")
{
//but since word is only on "bldgA"
//how can I get the next item in the list which
//is on the same line?
//print out the name of the person and then the duty
}
if (word == "bldgB")
{
//same as A
}
}
}
FileStreamReader.Close();
我的最终输出是
“你在 bldgA,你的名字是 fred,你的职责是午餐”
【问题讨论】:
-
我的建议是不要尝试一次性解析它。将其拆分为每个 /bldg?/ 的子列表
-
您的摘录应放入
标记中,以便按预期显示。
-
为什么是 C# 标签?他没有具体说明他希望如何解决这个问题。
-
@Harleqin:我不懂 C#。但是示例代码似乎是用 C# 编写的。
-
@johnny:请说明您使用的语言