asp.NET 臟字過濾算法
更新時間:2009年10月25日 10:15:24 作者:
asp.NET 臟字過濾算法,需要參考上一篇文章,大家可以比較下。
原文見http://www.dhdzp.com/article/20575.htm
但在我這里測試的時候,RegEx要快一倍左右。但是還是不太滿意,因為我們網(wǎng)站上臟字過濾用的相當(dāng)多,對效率已經(jīng)有了一些影響,經(jīng)過一番思考后,自己做了一個算法。在自己的機器上測試了一下,使用原文中的臟字庫,0x19c的字符串長度,1000次循環(huán),文本查找耗時1933.47ms,RegEx用了1216.719ms,而我的算法只用了244.125ms.
更新:新增一個BitArray,用于判斷某char是否在所有臟字中出現(xiàn)過??倳r間由244ms降到了34ms.
主要算法如代碼所示
private static Dictionary dic = new Dictionary();
private static BitArray fastcheck = new BitArray(char.MaxValue);
static void Prepare()
{
string[] badwords = // read from file
foreach (string word in badwords)
{
if (!dic.ContainsKey(word))
{
dic.Add(word, null);
maxlength = Math.Max(maxlength, word.Length);
fastcheck[word[0]] = true;
}
}
}
使用的時候
int index = 0;
while (index < target.Length)
{
if (!fastcheck[target[index]])
{
while (index < target.Length - 1 && !fastcheck[target[++index]]) ;
}
for (int j = 0; j < Math.Min(maxlength, target.Length - index); j++)
{
string sub = target.Substring(index, j);
if (dic.ContainsKey(sub))
{
sb.Replace(sub, "***", index, j);
index += j;
break;
}
}
index++;
}
但在我這里測試的時候,RegEx要快一倍左右。但是還是不太滿意,因為我們網(wǎng)站上臟字過濾用的相當(dāng)多,對效率已經(jīng)有了一些影響,經(jīng)過一番思考后,自己做了一個算法。在自己的機器上測試了一下,使用原文中的臟字庫,0x19c的字符串長度,1000次循環(huán),文本查找耗時1933.47ms,RegEx用了1216.719ms,而我的算法只用了244.125ms.
更新:新增一個BitArray,用于判斷某char是否在所有臟字中出現(xiàn)過??倳r間由244ms降到了34ms.
主要算法如代碼所示
復(fù)制代碼 代碼如下:
private static Dictionary dic = new Dictionary();
private static BitArray fastcheck = new BitArray(char.MaxValue);
static void Prepare()
{
string[] badwords = // read from file
foreach (string word in badwords)
{
if (!dic.ContainsKey(word))
{
dic.Add(word, null);
maxlength = Math.Max(maxlength, word.Length);
fastcheck[word[0]] = true;
}
}
}
使用的時候
復(fù)制代碼 代碼如下:
int index = 0;
while (index < target.Length)
{
if (!fastcheck[target[index]])
{
while (index < target.Length - 1 && !fastcheck[target[++index]]) ;
}
for (int j = 0; j < Math.Min(maxlength, target.Length - index); j++)
{
string sub = target.Substring(index, j);
if (dic.ContainsKey(sub))
{
sb.Replace(sub, "***", index, j);
index += j;
break;
}
}
index++;
}
您可能感興趣的文章:
相關(guān)文章
從請求管道深入剖析HttpModule的實現(xiàn)機制圖文介紹
想要了解底層的原理必須對請求處理過程和頁面的生命周期有點了解才方便您入門學(xué)習(xí)一下內(nèi)容,本文將詳細(xì)介紹2012-11-11
Repeater控件動態(tài)變更列(Header,Item和Foot)信息(重構(gòu)cs)
上一篇雖然它算不上是完全動態(tài)化,但它已經(jīng)達(dá)到初期想要的效果,現(xiàn)另開一篇,不是重新另外寫,而是想重構(gòu)cs的代碼,因為前一篇的代碼雖然簡單,但代碼冗余過多,感興趣的朋友可以參考下哈2013-03-03
DropDownList根據(jù)下拉項的Text文本序號排序
在某些時候表中沒有可以排序的字段同時呢也不想修改表結(jié)構(gòu),但它的項文本有序號這時就可以用這方法排序,感興趣的你可以參考下,或許本文知識點對你有所幫助2013-03-03
ASP.NET用戶注冊實戰(zhàn)(第11節(jié))
這篇文章主要介紹了ASP.NET用戶注冊實戰(zhàn),鞏固前10小節(jié)所學(xué)的全部知識,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2015-08-08

