C#添加敏感词-创新互联
publ创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:做网站、网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的焦作网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!ic class CheckStreamReader
{
//使用的数据:
private static HashSet hash = new HashSet();
private byte[] fastCheck = new byte[char.MaxValue];
private BitArray charCheck = new BitArray(char.MaxValue);
private int maxWordLength = 0;
private int minWordLength = int.MaxValue;
private static string[] badwords = { };
public CheckStreamReader()
{
if (hash == null || hash.Count <= 0)
{
//添加敏感词
string path = HttpContext.Current.Server.MapPath("~/config") + "/StreamReader.txt";
StreamReader sr = new StreamReader(path, Encoding.GetEncoding("utf-8"));
string strText = sr.ReadToEnd();
badwords = strText.Split('|');
InitializationText();
}
}
//初始化数据的代码:将敏感词加入的hash表中
private void InitializationText()
{
foreach (string word in badwords)
{
maxWordLength = Math.Max(maxWordLength, word.Length);
minWordLength = Math.Min(minWordLength, word.Length);
for (int i = 0; i < 7 && i < word.Length; i++)
{
fastCheck[word[i]] |= (byte)(1 << i);
}
for (int i = 7; i < word.Length; i++)
{
fastCheck[word[i]] |= 0x80;
}
if (word.Length == 1)
{
charCheck[word[0]] = true;
}
else
{
hash.Add(word);
}
}
}
//判断是否包含脏字的代码:
public bool HasBadWord(string text)
{
if (hash == null || hash.Count<=0)
{
string path = HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["ConfigPath"]) + "/StreamReader.txt";
StreamReader sr = new StreamReader(path, Encoding.GetEncoding("utf-8"));
string strText = sr.ReadToEnd();
badwords = strText.Split('|');
InitializationText();
}
int index = 0;
while (index < text.Length)
{
if ((fastCheck[text[index]] & 1) == 0)
{
while (index < text.Length - 1 && (fastCheck[text[++index]] & 1) == 0) ;
}
if (minWordLength == 1 && charCheck[text[index]])
{
return true;
}
for (int j = 1; j <= Math.Min(maxWordLength, text.Length - index - 1); j++)
{
if ((fastCheck[text[index + j]] & (1 << Math.Min(j, 7))) == 0)
{
break;
}
if (j + 1 >= minWordLength)
{
string sub = text.Substring(index, j + 1);
if (hash.Contains(sub))
{
return true;
}
}
}
index++;
}
return false;
}
}
网页名称:C#添加敏感词-创新互联
地址分享:http://hbruida.cn/article/ddhgph.html
网页名称:C#添加敏感词-创新互联
地址分享:http://hbruida.cn/article/ddhgph.html