Home > front end >  Find a words in text file then skip two lines then add a new line with words c#
Find a words in text file then skip two lines then add a new line with words c#

Time:12-27

i have a text file that contain texts like this

.end method

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

.line 83

i need to find ".method public onCreate" then skip the line after it and add "Hello World" in a new line

the text file will be like this

.end method

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

can any one help me with code in c# ?

this is my code :

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"
}

CodePudding user response:

You could introduce a variable which keeps track of a match (i.e. found).

I decided to update that variable with the value 2, and decrement it each line.

When the value equals 0, I do output "Hello World". (after this the value of found will keep decrementing...)

            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");
            }

CodePudding user response:

You can implement a simple Finite State Machine:

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;
}

Possible usage:

using System.IO;
using System.Linq;

...

var mclass2 = @"c:\MyFile.txt";

...

string[] lines = MyLines("mclass2").ToArray();
  •  Tags:  
  • c#
  • Related