简体   繁体   中英

Blocking Strings in a chat Upper/Lower case C#

I am attempting to create a word filter to block any words listed in a textfile from being broadcast in chat.

The initial code works fantastically but ONLY if the words being said in chat are IDENTICAL to words in the textfile.

I need a way for it to block the word regardless if it's in all uppercase, all lowercase or anything in between but it must match the word in the list exactly.

eg, it will not filter "ship, SHIP or ShIp" but it will filter.. "Sh**, SH**" you get the idea. I am open to other methods that don't include making a huge textfile list.

      foreach (var word in File.ReadAllLines("wordlist.txt"))
            {
                if (message.Contains(word))
                 player.SendToSelf(Channel.Reliable, ClPacket.GameMessage, "You Cannot Say That Here!");


            }

            return true;
}

I have tried

if (char.IsUpper(message[0]))
             player.SendToSelf(Channel.Reliable, ClPacket.GameMessage, "You Cannot Say That Here!");

Something like CurrentCulture/InvariantCultureIgnoreCase/OrdinalIgnoreCase could be used, but I'm not sure how to implement such things.

Would also be extremely beneficial to block words in foreign (other than En) language using foreign characters.

From this MSDN article on string.Compare :

public static class StringExtensions
{
   public static bool Contains(this String str, String substring, 
                               StringComparison comp)
   {                            
      if (substring == null)
         throw new ArgumentNullException("substring", 
                                         "substring cannot be null.");
      else if (! Enum.IsDefined(typeof(StringComparison), comp))
         throw new ArgumentException("comp is not a member of StringComparison",
                                     "comp");

      return str.IndexOf(substring, comp) >= 0;                      
   }
}

You can add this static class to your source and use StringComparison.InvariantCulture as your argument for StringComparison

if (message.Contains(word, StringComparison.InvariantCulture))
    //blah

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM