簡體   English   中英

當字符串中不出現搜索字符串時,String.indexOf返回非負索引

[英]String.indexOf returns non-negative index when search string does not occur in string

我正在解析一些日志文件以生成報告,但是在幾行中使用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;

預期:-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;
}

換行代碼

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

將ctIndex設置為line.SubString()后,您的方法不會檢查ctIndex是否等於-1。 然后,將“ CaptureTime =“的長度添加到ctIndex,然后預形成子字符串。

由於這些原因,我懷疑您的當前狀態的代碼對於不包含CaptureTime =值的日志消息將無法正常工作。 該功能行為是故意的嗎?

您不會處理在字符串右邊找不到CaptureTime=的情況。

  • 您擁有ctIndex = -1,然后將其添加12( CaptureTime=的長度)。 那給你11。
  • 然后,您在此之后找到第一個空格,它是時間戳和“ localhost”之間的空格。 那是第15位。
  • 然后,您從11到15獲得子字符串,即“ 4:19”。
  • 最后,您嘗試將其解析為很長的時間,顯然不是。

您需要實際檢查ctIndex == -1 ,然后正確處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM