C# 髒字過濾

來源:互聯網
上載者:User

這兩天突然想到了髒字過濾 就結合網上找到的資料自己寫了一個,髒字數量700+(效率不是很高 測試在110多KB的情況下比replace快 3-4倍)

測試結果圖 單位:秒

 

代碼

 

System.Text.StringBuilder sb = new System.Text.StringBuilder(text.Length);            string filterText = "需要過濾的髒字 以|分開";//髒字 可根據自己的方式用分隔字元            string[] filterData = filterText.Split('|');            foreach (var item in filterData)            {                char value = item[0];                if (dicList.ContainsKey(value))                    dicList[value].Add(item);                else                    dicList.Add(value, new List<string>() { item });            }            int count = text.Length;            for (int i = 0; i < count; i++)            {                char word = text[i];                if (dicList.ContainsKey(word))//如果在字典表中存在這個key                {                    int num = 0;//是否找到匹配的關鍵字  1找到0未找到                    var data = dicList[word].OrderBy(g => g.Length);//把該key的字典集合按 字元數排序(方便下面從少往多截取字串尋找)                    foreach (var wordbook in data)                    {                        if (i + wordbook.Length <= count)//如果需截取的字串的索引小於總長度 則執行截取                        {                            string result = text.Substring(i, wordbook.Length);//根據關鍵字長度往後截取相同的字元數進行比較                            if (result == wordbook)                            {                                num = 1;                                sb.Append(GetString(result));                                i = i + wordbook.Length - 1;//比較成功 同時改變i的索引                                break;                            }                        }                    }                    if (num == 0)                        sb.Append(word);                }                else                    sb.Append(word);            }            return sb.ToString();        }        /// <summary>        /// 替換星號        /// </summary>        /// <param name="value"></param>        /// <returns></returns>        private static string GetString(string value)        {            string starNum = string.Empty;            for (int i = 0; i < value.Length; i++)            {                starNum += "*";            }            return starNum;        }

 

 

 還有待最佳化的地方 

各位有更好的方法  還請分享指點一下   說明原理

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.