使用Substring查找出现次数

时间:2014-01-17 10:39:58

标签: c#

我正在用C#读取文件。我想从字符串中检查值。该行包括以下内容:

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

我想查找次数。我写了以下代码:

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

但抛出异常。

这样做的有效方法是什么?

3 个答案:

答案 0 :(得分:0)

Substring方法有两个参数,参见声明:

public string Substring(int startIndex,int length)

答案 1 :(得分:0)

这里有一些伪代码来计算:

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

答案 2 :(得分:0)

您可以使用此LINQ查询来实现文件的行并提取信息:

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