特定
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."
Run Code Online (Sandbox Code Playgroud)
如何从queryText获取stringList中所有字符串的总出现次数?
在上面的例子中,我想要一个返回3的方法;
private int stringMatches (string textToQuery, string[] stringsToFind)
{
//
}
Run Code Online (Sandbox Code Playgroud)
结果
太快了!
进行了几次性能测试,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;
}
Run Code Online (Sandbox Code Playgroud)
执行时间: 在使用秒表的10000次迭代循环中:
法比安:37-42毫秒
lazyberezovsky StringCompare:400-500毫秒
lazyberezovsky Regex:630-680毫秒
格伦:750-800毫秒
(为Fabians添加了StringComparison.Ordinal,以获得更高的速度.)
那可能也很快:
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;
}
Run Code Online (Sandbox Code Playgroud)