using System;
class MainClass {
public static void Main (string[] args) {
string text = "敏感词文本,巴拉巴拉巴拉巴拉222";
string[] sensitiveWords = { "222", "敏感" };
string censoredText = CensorText(text, sensitiveWords);
Console.WriteLine(censoredText);
}
public static string CensorText(string text, string[] sensitiveWords) {
foreach (var word in sensitiveWords) {
if (text.Contains(word)) {
string censor = new string('*', word.Length);
text = text.Replace(word, censor);
}
}
return text;
}
}
下面的没有用了
思路:
先遍历,把要屏蔽的字的下标保存起来,然后根据下标替换
下面是控制台的测试代码,可以直接用来测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaskWordTest
{
class Program
{
//模拟的屏蔽字库
public static List<string> wordStock = new List<string>();
//保存要屏蔽的字符串的索引
public static List<int> index = new List<int>();
static void Main(string[] args)
{
Console.WriteLine("当前屏蔽字库");
wordStock.Add("1");
wordStock.Add("四风");
wordStock.Add("风俗");
for (int i = 1; i < 10; i++)
{
wordStock.Add("你好" + i);
}
foreach (var item in wordStock)
{
Console.WriteLine(item);
}
Console.WriteLine();
Test();
}
private static void Test()
{
string readLine = string.Empty;
while (readLine != "0")
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("请输入一个字符串");
readLine = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Green;
MaskWordTest(readLine, 3);
Console.WriteLine();
}
}
//这里的num表示最大几个字连起来丢到屏蔽字库对比
//比如num = 3,str = “沙雕1”
//拆分开就是
//{"沙","雕","1"}
//{"沙雕","雕1"}
//{"沙雕1"}
private static void MaskWordTest(string str, int num)
{
index.Clear();
for (int i = 1; i < num + 1; i++)
{
if (i <= str.Length)
{
Test2(str, i);
}
}
foreach (var item in index)
{
str = str.Remove(item, 1);
str = str.Insert(item, "*");
}
Console.WriteLine(str);
}
//把字符串拆分开丢到屏蔽字库对比
private static void Test2(string s, int num)
{
char[] chs = s.ToCharArray();
string str = string.Empty;
for (int i = 0; i < chs.Length; i++)
{
if (chs.Length - num > i - 1)
{
string st = string.Empty;
for (int j = 0; j < num; j++)
{
st += chs[i + j];
}
JudgeIsExist(st, i);
}
}
}
///判断当前字符串是否为屏蔽字,如果是把下标记录下来
/// <param name="str"></param>
/// <param name="index">当前下标</param>
/// <returns></returns>
private static void JudgeIsExist(string str, int ind)
{
int num = ind - 1;
if (wordStock.Exists(w => w == str))
{
for (int i = 0; i < str.Length; i++)
{
num++;
if (!index.Exists(e => e == num))
{
index.Add(num);
}
}
}
}
}
}