【问题标题】:How to read back the line that looped c# by StringReader?如何读回StringReader循环c#的行?
【发布时间】:2020-10-13 02:04:13
【问题描述】:

有什么方法可以在 StringReader 中加入前一个(循环行)?因为我想遍历文本以查找特定单词,然后在找到后与上一行返回。

到目前为止我做了什么:

using (StringReader reader = new StringReader(currentText))
 {
   string line;
   var prevline = "";
   var newline = "";
   var des= "";
   while ((line = reader.ReadLine()) != null)
   {
     string[] splittedTxt = line.Split(new[] { " " },
      StringSplitOptions.RemoveEmptyEntries);

      if (line.Contains("Fee"))
      {
        for (int i = 0; i < splittedTxt.Length; i++)
        {
         des += splittedTxt[i] + " ";
         newline = prevline +" " + des;
        }
     }
   } 
}

【问题讨论】:

  • 你想通过一些例子来详细说明
  • 我实际上是从 pdf 创建一个新的数据表,我想在 excel 中找到包含费用的文本,但是在我使用 pdfReader 之后,这些行分成了文本和不同的行,所以我想在找到单词后加入回行
  • 代码中的pdfreader在哪里?
  • 我猜应该在 itextSharp 下 stackoverflow.com/questions/2550796/…
  • 分享pdf阅读器代码段

标签: c# split


【解决方案1】:

StringReader 仅用于向前读取文件。

字符串的问题是读取时需要处理编码才能正确存储和显示,而且编码大小不一。

这意味着你需要再往下一层处理流并向前和向后寻找,然后确定和处理字符串的编码差异。

查看更多详情和代码示例: How to read a text file reversely with iterator in C#

在您的情况下,您似乎只需要上一行。所以我认为不需要向后阅读,你只需要为每次迭代存储它,然后只在需要时使用它。看起来你已经拥有了大部分你需要的东西,你只需要像这样将 line 存储在 prevline 中:

while ((line = reader.ReadLine()) != null)
{
    string[] splittedTxt = line.Split(new[] { " " },
    StringSplitOptions.RemoveEmptyEntries);

    if (line.Contains("Fee"))
    {
        for (int i = 0; i < splittedTxt.Length; i++)
        {
           des += splittedTxt[i] + " ";
           newline = prevline +" " + des;
        }
    }
    prevline = line;
} 

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 2021-05-30
    • 2019-09-19
    相关资源
    最近更新 更多