2013-12-11 37 views
0

我已經創建了搜索算法來搜索Text.I中的任何字符串,只是希望計算返回的匹配項,並且只想通過一個鍵進行搜索。我已經通過搜索大小爲2 MB的文件中的單個字符'a'來測試性能,並且需要大約7秒。可以請您提出更好的算法或者如果我在這裏丟失了任何東西。本搜索算法的問題C#

public int SearchText(string fromString,string searchText,bool isCaseSensitive) 
     { 
      int searchTextLength=searchText.Length; 
      if (!isCaseSensitive) 
      { 
       fromString = fromString.ToLower(); 
       searchText = searchText.ToLower(); 
      } 
      int matchCount=0; 
      while (fromString.Length > searchText.Length) 
      { 
       int firstMatchIndex=fromString.IndexOf(searchText[0]); 
       if (firstMatchIndex > -1) 
       { 
        if (searchText == fromString.Substring(firstMatchIndex, searchTextLength)) 
         matchCount++; 
        fromString = fromString.Remove(0, firstMatchIndex + searchTextLength); 
       } 
       else 
        break; 
      } 
      return matchCount; 
     } 
+0

爲什麼你沒有使用string.contains()... ????? – Aravind

+0

因爲我還需要計數 – Rishikesh

回答

1

您正在創建不必要的臨時字符串到處都是。你可以把它改成這樣的事情..這應該更快:

public int SearchText(string fromString, string searchText, bool isCaseSensitive) { 
    int matchCount = 0; 

    var comparison = isCaseSensitive 
     ? StringComparison.InvariantCulture 
     : StringComparison.InvariantCultureIgnoreCase; 

    int foundIndex = fromString.IndexOf(searchText, 
     comparison); 

    while (foundIndex > -1) { 
     foundIndex = fromString.IndexOf(searchText, 
      foundIndex + 1, 
      comparison); 

     matchCount++; 
    } 

    return matchCount; 
} 

編輯:我測試了這一點。需要197ms來處理2MB的隨機數據

+0

謝謝你!!你是對的。我用相同的輸入檢查了你的代碼,實際上它只用了不到一秒鐘。我應該使用IndexOf檢查全文而不是首先檢查一個字符。我認爲在編寫代碼時我在某處丟失了。 – Rishikesh

1

嘗試使用正則表達式

public int SearchText(string fromString, string searchText, bool isCaseSensitive) 
{ 
     RegexOptions options = isCaseSensitive ? 
      RegexOptions.None : RegexOptions.IgnoreCase; 
     return Regex.Matches(fromString, Regex.Escape(searchText), options).Count; 
} 

編輯我LinqPad進行了測試,它需要113毫秒到2.5 MB Lorem存有的獲取計數。

+1

切記要逃避輸入,否則可能會產生意想不到的輸出。 –

+0

你有這個基準嗎? –

+0

謝謝你的替代方法。我總是傾向於忽略正則表達式的力量。用它來處理它,大約需要60-80ms,與西蒙建議的方法相似,在(50-70毫秒)的範圍內。通過執行這兩種方法測試10次。 – Rishikesh