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

C#髒字過濾算法

編輯:C#入門知識

public class DirtyWordOper
    {
        private static Dictionary<string, object> hash = new Dictionary<string, object>();
        private static BitArray firstCharCheck = new BitArray(char.MaxValue);//把髒詞的第一個字符記錄下來
        private static BitArray allCharCheck = new BitArray(char.MaxValue);//把每一個個髒詞的所有字符都記錄下來
        private static int maxLength = 0;//
        private static bool onlyOne = true;

        #region
        /// <summary>
        /// 返回替換後的字符串 字符串的長度不變
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string Replace(string text)
        {
            if (onlyOne)
            {
                Init();//初始化數據 執行一次就不會執行了
                onlyOne = false;
            }
            if (!isDirtyword(text))
            {
                return text;
            }
            //獲取替換操作表
            List<DetailRepModel> drlist = GetList(text);
            //執行替換操作
            return Replace2(text, drlist);
        }

        /// <summary>
        /// 初始化用  只執行一次
        /// </summary>
        /// <param name="text"></param>
        private static void Init()
        {
            string[] badwords = DirtyWordData.DirtyKeyword.Split(|);
            foreach (string bw in badwords)
            {
                string[] strarrtemp = bw.Split(&);
                string word = strarrtemp[0];
                word = word.Trim();//去掉數據中的空格及格式 符號
                word = word.Replace("/r", "");
                word = word.Replace("/n", "");
                if (word == "")
                {
                    break;
                }
                if (!hash.ContainsKey(word))
                {
                    hash.Add(word, null);
                    maxLength = Math.Max(maxLength, word.Length);
                    firstCharCheck[word[0]] = true;

                    foreach (char c in word)
                    {
                        allCharCheck[c] = true;
                    }
                }
            }
        }
        /// <summary>
        /// 是否包含 了 髒 詞
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private static bool isDirtyword(string text)
        {
            int index = 0;
            //int offset = 0;
            while (index < text.Length)
            {
                //如果第一個字符都不符合
                if (!firstCharCheck[text[index]])
                {// 直接找到與髒詞第一字符相同為止
                    while (index < text.Length - 1 && !firstCharCheck[text[++index]]) ;
                }
                for (int j = 1; j <= Math.Min(maxLength, text.Length - index); j++)
                {
             &nb

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved