-1

I am reading a file in C#. I want to check value from a string. The line consists as following:

   20  EMP HAPPENS 5 TIMES.   
   40  SUP HAPPENS 7 TIMES. 

I want to find the number of times. I have written the following code:

if(line.IndexOf(HAPPENS) + 1 > 0)
     arrayLength= int.Parse(line.Substring(line.IndexOf(HAPPENED) + OCCURS.Length + 1).Trim("."));

But exception is thrown.

What is the efficient way to do that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

0

Substring method takes two params, see declaration:

public string Substring(int startIndex,int length)
Shhade Slman
  • 263
  • 2
  • 10
0

Here some psuedo code to get your count:

//read lines from file
foreach (string line in lines){
   if (line.Contains("HAPPENS")){
       int happensindex = line.IndexOf("HAPPENS");
       int timesindex = line.IndexOf("TIMES");
       int happenscount;

       int indexCount = happensindex  + 8;
       int countLength = happensindex - timesindex - 9;
       if (int.TryParse(line.Substring(indexCount , countLength), out happenscount){
           //happenscount contains your count
       }
   }
}
Peter
  • 27,590
  • 8
  • 64
  • 84
0

You can use this LINQ query to real the lines of the file and extract the informations:

var allOccurrences = File.ReadLines("Path")
    .Select(l => new { HappenIndex = l.IndexOf(" HAPPENS "), Line = l })
    .Where(LineInfo => LineInfo.HappenIndex >= 0)
    .Select(LineInfo =>  
    {
        var retVal = new { LineInfo, What = LineInfo.Line.Substring(0, LineInfo.HappenIndex).Trim(), Occurences = (int?)null };
        int timesIndex = LineInfo.Line.IndexOf(" TIMES", LineInfo.HappenIndex + " HAPPENS ".Length);
        if(timesIndex >= 0)
        {
            int behindHappen = LineInfo.HappenIndex + " HAPPENS ".Length;
            string times = LineInfo.Line.Substring(behindHappen, timesIndex - behindHappen).Trim();
            int occurences;
            if(int.TryParse(times, out occurences))
                retVal = new { LineInfo, retVal.What, Occurences = (int?)occurences };
        }
        return retVal;
    })
    .Where(x => x.Occurences.HasValue)
    .ToList();

foreach (var occ in allOccurrences)
{ 
    Console.WriteLine("Line contains '{0}' {1} times", occ.What, occ.Occurences);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939