首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >逐行阅读

逐行阅读
EN

Stack Overflow用户
提问于 2009-09-29 22:34:48
回答 4查看 422关注 0票数 0

我有一个生成纯文本文件的程序。结构(布局)总是相同的。示例:

文本文件:

代码语言:javascript
运行
AI代码解释
复制
LinkLabel
"Hello, this text will appear in a LinkLabel once it has been
added to the form. This text may not always cover more than one line. But will always be surrounded by quotation marks."
240, 780

因此,要解释该文件中发生了什么:

代码语言:javascript
运行
AI代码解释
复制
Control
Text
Location

当单击表单上的一个按钮,用户从OpenFileDialog对话框中打开其中一个文件时,我需要能够读取每一行。从顶部开始,我想检查它是什么控件,然后从第二行开始,我需要能够获取引号中的所有文本(不管是一行还是多行),在下一行(在结束引号之后),我需要提取位置(240,780).我想了几种方法来解决这个问题,但是当我把它写下来并付诸实施时,它就没有多大意义了,最后我想出了一些不起作用的方法。

以前有人这样做过吗?有没有人能提供任何帮助,建议或建议,我如何去做这件事?

我已经查找了CSV文件,但对于看起来如此简单的事情来说,这似乎太复杂了。

谢谢贾塞

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-09-29 22:47:37

您可以使用正则表达式从文本中获取行:

代码语言:javascript
运行
AI代码解释
复制
MatchCollection lines = Regex.Matches(File.ReadAllText(fileName), @"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)\r\n");
foreach (Match match in lines) {
   string control = match.Groups[1].Value;
   string text = match.Groups[2].Value;
   int x = Int32.Parse(match.Groups[3].Value);
   int y = Int32.Parse(match.Groups[4].Value);
   Console.WriteLine("{0}, \"{1}\", {2}, {3}", control, text, x, y);
}
票数 2
EN

Stack Overflow用户

发布于 2009-09-29 22:43:45

我将尝试写下算法,以及解决这些问题的方法(在注释中):

代码语言:javascript
运行
AI代码解释
复制
// while not at end of file
  // read control
  // read line of text
  // while last char in line is not "
    // read line of text
  // read location

试着编写一段代码来完成每条注释都说的话,这样你就能找到答案了。

HTH。

票数 2
EN

Stack Overflow用户

发布于 2009-09-29 22:52:49

您正在尝试实现一个解析器,最好的策略是将问题分成更小的部分。您需要一个TextReader类,使您能够读取行。

应该将ReadControl方法分为三种方法:ReadControlTypeReadTextReadLocation。每个方法只负责读取它应该读取的项,并将TextReader保留在下一个方法可以拾取的位置。就像这样。

代码语言:javascript
运行
AI代码解释
复制
public Control ReadControl(TextReader reader)
{
    string controlType = ReadControlType(reader);
    string text = ReadText(reader);
    Point location = ReadLocation(reader);
    ... return the control ...
}

当然,ReadText是最有趣的,因为它跨越多行。实际上,它是一个调用TextReader.ReadLine的循环,直到该行以引号结尾为止:

代码语言:javascript
运行
AI代码解释
复制
private string ReadText(TextReader reader)
{
    string text;
    string line = reader.ReadLine();
    text = line.Substring(1); // Strip first quotation mark.
    while (!text.EndsWith("\"")) {
        line = reader.ReadLine();
        text += line;
    }
    return text.Substring(0, text.Length - 1); // Strip last quotation mark.
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1496421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档