Unity 3D 屏蔽字 敏感字 Hashset版

using System.Collections.Generic;
using UnityEngine;

public class MyBadWordsTest : MonoBehaviour
{
    public TextAsset allBadWords;
    private int theLongestNum = 0;
    private int theShortestNum = 10;
    private void Start()
    {
        string testStr = "电脑手机书本";
        var all = allBadWords.text.Split(',');

        HashSet badWords = new HashSet();

        foreach (var s in all)
        {
            if (string.IsNullOrEmpty(s) || s.Length < 1)
            {
                continue;
            }
            badWords.Add(s);
            if (s.Length > theLongestNum)
            {
                theLongestNum = s.Length;
            }
            if (s.Length < theShortestNum)
            {
                theShortestNum = s.Length;
            }
        }


        string strTemp = string.Empty;

        for (int i = 0; i < testStr.Length; i++)
        {
            if (theShortestNum == theLongestNum)
            {
                if (i + theShortestNum > testStr.Length)
                {
                    break;
                }
                strTemp = testStr.Substring(i, theShortestNum);
                if (badWords.Contains(strTemp))
                {
                    Debug.Log(strTemp);
                }
                continue;
            }
            for (int j = theShortestNum; j < theLongestNum; j++)
            {
                if (i + j > testStr.Length)
                {
                    break;
                }
                strTemp = testStr.Substring(i, j);
                if (badWords.Contains(strTemp))
                {
                    Debug.Log(strTemp);
                }
            }
        }
    }
}

封装一下就可以用了。效率基本满足。

你可能感兴趣的:(Unity3D,开发日常随笔)