【问题标题】:Find a words in text file then skip two lines then add a new line with words c#在文本文件中查找一个单词然后跳过两行然后添加一个带有单词的新行 c#
【发布时间】:2021-12-26 14:31:29
【问题描述】:

我有一个包含此类文本的文本文件

.end method

.method public onCreate(Landroid/os/Bundle;)V
.locals 7

.line 83

我需要找到“.method public onCreate”然后跳过它后面的行并在新行中添加“Hello World”

文本文件会是这样的

.end method

.method public onCreate(Landroid/os/Bundle;)V
.locals 7
Hello World
.line 83

谁能帮我写c#代码?

这是我的代码:

string pubmethod = ".method public onCreate(Landroid/os/Bundle;)V";

var x = File.ReadAllLines(mclass2);

var y = x.Where(w => w.Contains(pubmethod));

foreach (var item in y)
{
    // skip line and add  "Hello World"
}

【问题讨论】:

  • 你自己试过什么?那次尝试在哪里/为什么失败了?
  • 我可以检查文件是否包含这个“.method public onCreate”,但我不能在行后添加单词
  • @user17766888 欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 以了解如何提高问题的质量。然后edit你的问题包括你的源代码作为工作minimal reproducible example,它可以被其他人编译和测试。请显示您尝试过的尝试以及您从尝试中得到的问题/错误消息。
  • 我编辑了这个问题,现在我怎样才能跳过行并添加“Hello World”?
  • 文本文件在概念上是一个字节流。但实际上,它是磁盘上的一个文件,文件中的每个字节都与磁盘上的一个物理字节匹配。你不能打开一个文件,读一点,然后在文件中间添加一行。您需要从一个文件读取并写入另一个文件。一个你满意的读/写操作完成,删除原来的文件并重命名新的匹配

标签: c#


【解决方案1】:

您可以引入一个跟踪匹配项的变量(即found)。

我决定用值 2 更新该变量,并在每一行递减它。

当值等于 0 时,我会输出“Hello World”。 (在此之后found 的值将继续递减......)

            string pubmethod = ".method public onCreate(Landroid/os/Bundle;)V";
            var x = File.ReadAllLines(mclass2);
            //var y = x.Where(w => w.Contains(pubmethod));
            int found = 0;
            foreach (var item in x)
            {
                if (item.Contains(pubmethod)) found = 2;
                Console.WriteLine(item);
                found--;
                if (found==0) Console.WriteLine("Hello World");
            }

【讨论】:

    【解决方案2】:

    您可以实现一个简单的Finite State Mahine:

    private static IEnumerable<string> MyLines(string fileName) {
      int state = 1;
    
      foreach(string line in File.ReadLines(fileName)) 
        if (state == 1) {
          if (line == ".method public onCreate(Landroid/os/Bundle;)V")
            state = 2;
    
          yield return line;
        }
        else if (state == 2) {
          yield return "Hello World";
    
          state = 3;
        } 
        else
          yield return line;
    }
    

    可能的用法:

    using System.IO;
    using System.Linq;
    
    ...
    
    var mclass2 = @"c:\MyFile.txt";
    
    ...
    
    string[] lines = MyLines("mclass2").ToArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多