C# 屏蔽關鍵字的實現方法

來源:互聯網
上載者:User

建立一個txt的文本(代碼中讀取這個文字文件路徑就行,命名隨意)

裡面的內容一行代表一個,因為我是按行來遍曆迴圈讀取要屏蔽的關鍵字.然後用一個*號來屏蔽一個關鍵字,

例如: 在論壇中輸出"草泥馬",涉及到一些比較敏感的話題、名字,在一些推廣比較火爆的網站裡,都是不允許的,所以這裡會只顯示"***"。

這裡代碼下面我給出來了,注釋都比較詳細..不懂的可以留言問我.希望博友每天能進步一點點..

複製代碼 代碼如下: /// <summary>
/// 屏蔽非法字串(如果有出現非法字元,那麼用"***"來替換)
/// </summary>
/// <param name="strText">要檢測的字串</param>
/// <returns>返還一個健康的字元</returns>
public static string CheckKeyword(string strText)
{
IList<string> list = new List<string>(); //執行個體化一個資料集
string strpath = System.Web.HttpContext.Current.Server.MapPath("function/keyword.txt"); //擷取文字文件路徑
int a =strpath.LastIndexOf("IFSns");
int b =strpath.IndexOf("function");
string m = strpath.Substring(a+5, b - a - 6);
string PathTxt = strpath.Replace(m, ""); //擷取調用這個方法的相對路徑
FileStream fs = new FileStream(PathTxt, FileMode.Open, FileAccess.Read); //開啟txt文檔,將資料存到檔案流中
StreamReader reader = new StreamReader(fs, Encoding.Default); //檔案讀取
string strLine = reader.ReadLine();
while (strLine!=null&&strLine.Length != 0) //有資料
{
list.Add(strLine.Trim().Replace(" ","")); //如果讀取到的資料有空格,則刪除空格,並且存到string資料集中
strLine = reader.ReadLine(); //每讀取一次,從該行下一行開始繼續讀取
}
fs.Close(); //關閉檔案流
foreach (string str in list) //迴圈遍曆檔案流
{
if (strText.Contains(str))
{
int lg = str.Length;
string sg = "";
for (int i = 0; i < lg; i++)
{
sg+="*";
}
strText = strText.Replace(str, sg); //如果含有txt文檔中的關鍵字,則替換為"***"
}
}
return strText;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.