我创建了搜索算法来搜索Text中的任何字符串。我只想要返回的匹配计数,并且只想搜索一个键。我已经通过在大小为2 mb的文件中搜索单个字符'a'来测试性能,大约花了7秒。你能建议更好的算法,或者我在这里遗漏了什么。
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 :(得分: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;
}
编辑:我测试了这个。处理2MB随机数据需要 197ms 。
答案 1 :(得分: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中对此进行了测试,从LMBM Ipsum的2.5 MB获取计数需要113 ms。