程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.NET 髒字過濾算法

asp.NET 髒字過濾算法

編輯:ASP.NET基礎
原文見http://www.jb51.net/article/20575.htm
但在我這裡測試的時候,RegEx要快一倍左右。但是還是不太滿意,因為我們網站上髒字過濾用的相當多,對效率已經有了一些影響,經過一番思考後,自己做了一個算法。在自己的機器上測試了一下,使用原文中的髒字庫,0x19c的字符串長度,1000次循環,文本查找耗時1933.47ms,RegEx用了1216.719ms,而我的算法只用了244.125ms.
更新:新增一個BitArray,用於判斷某char是否在所有髒字中出現過。總時間由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++;
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved