C#,优化查找指定字符串的操作。

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;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值