-2

Iam new in C# and have some problem. I open a file, but they are large, constains +700 000 lines. In this textfile, Iam looking for a NUMBER of line which contains "mySecretText". Now, I need to search text from line from NUMBER+1 to someOhherLine (for eg. for(line1000; line2000; line++){})

Now my code looks like:

        while ((line = file.ReadLine()) != null)
        {
            i++;
            if (line.Contains("mySecretWord"))
            {
                System.Console.WriteLine("YES");
                System.Console.WriteLine(i);
                break;
            }
        }

How to write a loop that read/search only lines <1000; 2000> ??

TMachna
  • 279
  • 1
  • 2
  • 10
  • 1
    have you exhausted all of your options for example a google search ..? take a look here for starters..http://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp if that doesn't suffice then look here [C# Code Samples](http://www.google.com) – MethodMan Dec 22 '14 at 17:18

3 Answers3

1

You can modify your loop as shown below to search only within specified range (i.e. in lines between 1000 and 2000):

while ((line = file.ReadLine()) != null)
{
    i++;
    if (i>=1000 && i<=2000 && line.Contains("mySecretWord"))
    {
        System.Console.WriteLine("YES");
        System.Console.WriteLine(i);
        break;
    }
}

or, in more elegant and speed-optimized form using else if condition statement:

while ((line = file.ReadLine()) != null)
{
    i++;
    if (i < 1000) continue;
    else if (i > 2000) break;
    else if (line.Contains("mySecretWord"))
    {
        System.Console.WriteLine("YES");
        System.Console.WriteLine(i);
        break;
     }
}

Note: continue; in first if condition is optional: that line could be written as simply if (i < 1000) {}. Hope this will help.

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
  • The answer by @coding-orange is preferred as it will won't continue reading the file after the upper limit has been reached – tddmonkey Dec 22 '14 at 17:24
1
for (int i = 0; i < start; ++i){
    file.ReadLine();
}
for (int i = start; i < finish; ++i){
    if(file.ReadLine().Contains("mySecretWord")){
            System.Console.WriteLine("YES");
            System.Console.WriteLine(i);
            break;
}

This will keep you from wasting any time reading lines after the range you're looking for.

Coding Orange
  • 548
  • 4
  • 7
0

I think this does what you want:

    var i = 0;
    var @from = 1000;
    var to = 2000;
    while ((line = file.ReadLine()) != null)
    {
        i++;

        if (i < @from)
            continue;

        if (i > to)
            break;

        if (line.Contains("mySecretWord"))
        {
            System.Console.WriteLine("YES");
            System.Console.WriteLine(i);
            break;
        }
    }
Dusty Lau
  • 591
  • 4
  • 18