如何解析文本文件?
基本上,我需要有人帮助我或向我展示代码,使我能够从我称为 c1.txt 的文件中读取名称和价格。
这是我已经拥有的。
TextReader c1 = new StreamReader("c1.txt");
if (cse == "c1")
{
string compc1;
compc1 = c1.ReadLine();
Console.WriteLine(compc1);
Console.WriteLine();
compcase = compc1;
compcasecost = 89.99;
}
另外,如何选择从文本文档中读取的行也很棒。
Basically I need someone to help me or show me the code that will allow me to read a name and a price from a file i have called c1.txt.
This is what i already have.
TextReader c1 = new StreamReader("c1.txt");
if (cse == "c1")
{
string compc1;
compc1 = c1.ReadLine();
Console.WriteLine(compc1);
Console.WriteLine();
compcase = compc1;
compcasecost = 89.99;
}
also how to select a line to read from a text document would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还没有告诉我们文本文件的格式。我将假设以下内容:
您也没有指定输出。我将假设以下内容:
然后以下内容将读取这样的文件并产生所需的输出。
如果您的分隔符不同,那么您需要将参数
'|'
更改为方法String.Split
(在名为String
的实例上调用)line
为line.Split('|')
)。如果您的格式需要不同,那么您需要使用“
如果您有任何问题请告诉我”这一行。
You haven't told us the format of the text file. I am going to assume the following:
You also didn't specify the output. I am going to assume the following:
Then the following will read such a file and produce the desired output.
If your separator is different then you need to change the parameter
'|'
to the methodString.Split
(invoked on the instance ofString
namedline
asline.Split('|')
).If your format needs to be different then you need to play with the line
Let me know if you have any questions.
您还可以尝试使用解析帮助器类作为起点,例如 http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-class。
You can also try using a parsing helper class as a starting point, such as the one described at http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-class.
它给出的结果与@Jason 的方法相同,但我认为这是一个优化版本。
It gives the same results as @Jason's method, but I think this is an optimized version.