[英]The fastest way to count string occurences in another string in c#
我必須計算一個很長的字符串中的字符串出現次數(純文本約30mb),現在我使用以下代碼: int count = new Regex(Regex.Escape(stringThatIamLookingFor)).Matches(stringToSearchIn).Count;
但是太慢了。 在i7和16GB內存上大約需要3分鍾。 示例數據為:
43.996442,-31.768039
43.996432,-31.768039
43.996432,-31.768049
43.996422,-31.768049
43.996422,-31.768059
我想算一下(例如) .7
有沒有比regeex更快的方法?
到目前為止,最快的功能是:(我只需要檢查兩個字符。)
public int countOccurences2(string source, char charOne, char charTwo)
{
int count = 0;
for (int i=0; i<=source.Length-1; i=i+2)
if (source[i] == charOne && source[i + 1] == charTwo) { count++; }
return count;
}
來自這個問題: 如何計算一個字符串中一個字符串的出現次數?
以下代碼似乎是性能最高的:
int count = 0, n = 0;
if(substring != "")
{
while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
{
n += substring.Length;
++count;
}
}
Richard Watson在提到的問題中提供的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.