当字符串中没有出现搜索字符串时,String.indexOf返回非负索引

0 c# string indexof

我正在解析一些日志文件以进行报告,但String.IndexOf()在几行上得到了奇怪的结果.在这里使用C#.最容易用一些代码解释.

String line = "Jun 29 14:34:19 localhost axis2_http_server: CEF:0|AOPTIX|IRIS|4.1.0.1664.2839|AD214030000301-2610017|114|SDK_ACCESS|4|time=1340980459 comp=10 compinfo=CAPTURE from=8 result=0 user=Admin thread=1305:1962 msg=ation=0.00, faceColor=11.49 HR Face is ICAO compliant, inter-pupil distance=140.00. No match found on LEFT eye (database is empty). LEFT_uid=-1, blacklist=0 No match found on RIGHT eye (database is empty). RIGHT_uid=-1, blacklist=0 CAPTURE successfully completed - SOAP response sent. ";
int ctIndex = line.IndexOf("CaptureTime=");
return ctIndex;
Run Code Online (Sandbox Code Playgroud)

预期:-1
实际:11

这只发生在大约一个日志文件中的2行.

实际实施的方法

private TimeSpan parseDuration(string line)
{
    int ctIndex = line.IndexOf("CaptureTime=");
    ctIndex = ctIndex + "CaptureTime=".Length;
    int endIndex = line.IndexOf(" ", ctIndex);
    string sDuration = line.Substring(ctIndex, endIndex - ctIndex);
    long duration;
    if (!long.TryParse(sDuration, out duration))
    {
        Console.WriteLine("Error Parsing Duration");
        return TimeSpan.Zero;
    }
    duration *= 1000;
    TimeSpan tsDuration = new TimeSpan(duration*1000);
    return tsDuration;
}
Run Code Online (Sandbox Code Playgroud)

换行代码

try{
    StreamReader sr = new StreamReader(FilePath);
    string line = sr.ReadLine();
    while(line != null)
    {
         TimeSpan ts = parseDuration(line);
         line = sr.ReadLine();
    }
catch(Exception ex){}
finally{sr.close();}
Run Code Online (Sandbox Code Playgroud)

Sha*_*rde 6

将其设置为line.SubString()后,您的方法不会检查ctIndex是否等于-1.然后,您将"CaptureTime ="的长度添加到ctIndex,然后预先形成子字符串.

我怀疑由于这些原因,当前状态的代码无法正常处理不包含CaptureTime =值的日志消息.是否有意图的功能行为?