软件编程
位置:首页>> 软件编程>> C#编程>> C# 屏蔽关键字的实现方法

C# 屏蔽关键字的实现方法

  发布时间:2023-10-10 15:15:50 

标签:C#,屏蔽关键字

新建一个txt的文本C# 屏蔽关键字的实现方法(代码中读取这个文本文档路径就行,命名随意)

里面的内容一行代表一个,因为我是按行来遍历循环读取要屏蔽的关键字.然后用一个*号来屏蔽一个关键字,

例如: 在论坛中输出"草泥马",涉及到一些比较敏感的话题、名字,在一些推广比较火爆的网站里,都是不允许的,所以这里会只显示"***"。
C# 屏蔽关键字的实现方法
 这里代码下面我给出来了,注释都比较详细..不懂的可以留言问我.希望博友每天能进步一点点..
 


  /// <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;
        }
 

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com