给定
var stringList = new List<string>(new string[] {
"outage","restoration","efficiency"});
var queryText = "While walking through the park one day, I noticed an outage",
"in the lightbulb at the plant. I talked to an officer about",
"restoration protocol for public works, and he said to contact",
"the department of public works, but not to expect much because",
"they have low efficiency."
如何从queryText获取stringList中所有字符串的出现总数?
在上面的例子中,我想要一个返回 3 的方法;
private int stringMatches (string textToQuery, string[] stringsToFind)
{
//
}
结果
说话太早了!
进行了几次性能测试,Fabian 的这个代码分支快了很多:
private int stringMatches(string textToQuery, string[] stringsToFind)
{
int count = 0;
foreach (var stringToFind in stringsToFind)
{
int currentIndex = 0;
while ((currentIndex = textToQuery.IndexOf(stringToFind , currentIndex, StringComparison.Ordinal)) != -1)
{
currentIndex++;
count++;
}
}
return count;
}
执行时间: 在使用秒表的 10000 次迭代循环中:
费边:37-42毫秒
lazyberezovsky 字符串比较:400-500 毫秒
lazyberezovsky 正则表达式:630-680 毫秒
格伦:750-800 毫秒
(将 StringComparison.Ordinal 添加到 Fabians 答案以提高速度。)