You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

102 lines
2.5 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text;
namespace Sog.Service
{
public class DirtyService : Singleton<DirtyService>
{
private Dictionary<string, int> m_dirtyDict = new Dictionary<string, int>();
public void InitFromFile(string filename)
{
if (!File.Exists(filename))
{
TraceLog.Error("DirtyService.InitFromFile file {0} not exists", filename);
return;
}
//这样支持reload
m_dirtyDict.Clear();
string[] allline = File.ReadAllLines(filename);
foreach(var line in allline)
{
if(string.IsNullOrEmpty(line))
{
continue;
}
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
if(line.Length < 2)
{
continue;
}
string lowLine = line.ToLower();
if (m_dirtyDict.ContainsKey(lowLine))
{
continue;
}
//转成小写
m_dirtyDict.Add(lowLine, 1);
}
}
// true表示有字符被替换
public bool ReplaceDirtyText(string content, out string outcontent)
{
outcontent = content;
string lowContent = content.ToLower();
char[] charArray = null;
//bool bReplace = false;
foreach (var dirty in m_dirtyDict.Keys)
{
//可能包含同一个脏词多次,所以要遍历
int index = lowContent.IndexOf(dirty);
while(index >= 0)
{
if(charArray == null)
{
charArray = content.ToArray();
}
for (int i = 0; i < dirty.Length; i++)
{
charArray[index + i] = '*';
}
index = lowContent.IndexOf(dirty, index + dirty.Length);
}
}
if(charArray == null)
{
return false;
}
StringBuilder builder = new StringBuilder(charArray.Length);
builder.Append(charArray);
outcontent = builder.ToString();
return true;
}
}
}