https://www.imooc.com/article/27299
此函数基于IndexOf方法搜索一个字符非常快这个事实的。
基本想法非常的简单,这个方法先搜索这个单词的第一个字符。如果一旦找到,它检测下一个的字符,该代码是有点乱,因为它包含了很多小的优化。例如,我发现,如果该方法在启动检测这个词的其余部分的“for”循环之前检查第二个字符(第一个已近被找到),平均性能将会更好。
作者:冉冉说
链接:https://www.imooc.com/article/27299
来源:慕课网
static int FastIndexOf(string source, string pattern)
{
bool found;
//搜索的要比原字符短
int limit = source.Length - pattern.Length + 1;
if (limit < 1)
return -1;
// Store the first 2 characters of "pattern"
char c0 = pattern[0];
char c1 = pattern.Length > 1 ? pattern[1] :' ';
// Find the first occurrence of the first character
int first = source.IndexOf(c0, 0, limit);
while (first != -1)
{
// Check if the following character is the same like the 2nd character of "pattern"
if (pattern.Length > 1 && source[first + 1] != c1)
{
first = source.IndexOf(c0, ++first, limit - first);
continue;
}
// Check the rest of "pattern" (starting with the 3rd character)
found = true;
for (int j = 2; j < pattern.Length; j++)
if (source[first + j] != pattern[j])
{
found = false;
break;
}
// If the whole word was found, return its index, otherwise try again
if (found)
return first;
first = source.IndexOf(c0, ++first, limit - first);
}
return -1;
}