The online racing simulator
How to make a swear filter in C#?
As I try the swears on a filter but my problem is how to load them to swear list.

I used LFS External for my base.

I tried to make this..
From FileInfo.cs
static public byte GetSwears(string Swears)
{
StreamReader Sr = new StreamReader(UserInfo + "\\swears.txt");

string line = null;
while ((line = Sr.ReadLine()) != null)
{
if (line.Substring(0, 6) == "Swears")
{
string[] Msg = line.Split('=');
if (Msg[1].Trim() == Swears)
{
Sr.Close();
return 1;
}
}
}
Sr.Close();
return 0;
}

From: private void Form1_Load(object sender, EventArgs e)
if (System.IO.File.Exists(UserInfo + "\\penalty\\swears.txt") == false)
{
System.IO.File.Create(UserInfo + "\\penalty\\swears.txt");
}

Form1.cs
Swears Region
string SwearFilter = Msg.ToLower();
int Swears = 0;
{
if (SwearFilter.Contains (""))
{
StreamReader Sr = new StreamReader(UserInfo + "\\penalty\\swears.txt");
string TempSr = Sr.ReadToEnd();
string line = null;
while ((line = Sr.ReadLine()) != null)
{
if (line.Substring(0, 6) == "Swears")
{
string[] Msg1 = line.Split('=');
if [COLOR=Blue](Msg[1].GetTypeCode() == Swears)[/COLOR]
{
Sr.Close();
}
}
}
InSim.Send_MST_Message("/msg ^4|^7 " + Connections[GetConnIdx(MSO.UCID)].PlayerName + " was fined for swearing");
}
}

Error: 7 Operator '==' cannot be applied to operands of type 'System.TypeCode' and 'int'

is my coding is wrong or just really wrong i need help
I'm really not sure what your code is doing, but if I was going to make a swear filter, I'd do something like this.

Presuming you have a file called "swear.txt" in the same folder as your program's exe file that has a banned word on each line:

boobs
willy
knickers
thatcher

First of all I would load that file into memory when the programs starts, with some simple code like this:

// List to store swear words.
List<string> swearwords = new List<string>();

void LoadSwearWords()
{
// Get the path to the 'swear.txt' file.
string file = Path.Combine(Environment.CurrentDirectory, "swear.txt");

// Open text file for reading.
using (TextReader reader = new StreamReader(file))
{
// Loop through each line in the file.
string line;
while ((line = reader.ReadLine()) != null)
{
// Remove any whitespace and cast to lower case.
string word = line.Trim().ToLower();

// Add to list in memory.
this.swearwords.Add(word);
}
}
}

Once I had the list of swear words in memory, I would then need some code to check if a message contained a swear word.

bool MessageContainsSwearWord(string message)
{
// This regex splits words, trims whitespace and removes punctuation.
string[] words = Regex.Split(message, @"\W+");

// Loop through each word and check if it's a swear word.
foreach (string word in words)
{
if (this.swearwords.Contains(word.ToLower()))
{
return true;
}
}
return false;
}

The MessageContainsSwearWord method returns true if the message contains a swearword or false otherwise. You could use it like this:


string message = "This message contains the word boobs";

if (MessageContainsSwearWord(message))
{
Console.WriteLine("That message is filthy!");
}
else
{
Console.WriteLine("Aww, what a well-spoken boy.");
}

// OUTPUT: That message is filthy!

I hope that helps!

You can download my test project below (requires VS Express 2010).
Attached files
SwearFilter.zip - 7 KB - 330 views
#3 - amp88
Quote from DarkTimes :
// List to store swear words.
List<string> swearwords = new List<string>();

void LoadSwearWords()
{
// Get the path to the 'swear.txt' file.
string file = Path.Combine(Environment.CurrentDirectory, "swear.txt");

// Open text file for reading.
using (TextReader reader = new StreamReader(file))
{
// Loop through each line in the file.
string line;
while ((line = reader.ReadLine()) != null)
{
// Remove any whitespace and cast to lower case.
string word = line.Trim().ToLower();

// Add to list in memory.
this.swearwords.Add(word);
}
}
}


You'd be better off with a Set here rather than an List. Depending on the implementation it should give you O(1) access rather than O(n) for the list. I'm not familiar with the C# syntax for a set though.
Won't someone please think of the children!
Quote from amp88 :You'd be better off with a Set here rather than an List. Depending on the implementation it should give you O(1) access rather than O(n) for the list. I'm not familiar with the C# syntax for a set though.

Hmm, is that true? I thought a set was between O(1) and O(n) in performance. It's not O(n) as there is not a 1 to 1 relation between the performance and the number of items, but because of the hashing process it's not actually O(1) either. Ah, I dunno. Well anyway, yeah a set will probably be faster in .NET, I wouldn't be able to say for sure without doing some performance tests. A generic list is plenty fast enough for this operation though and I've rarely ever seen a set used in .NET code.
#6 - amp88
Quote from DarkTimes :Hmm, is that true? I thought a set was between O(1) and O(n) in performance. It's not O(n) as there is not a 1 to 1 relation between the performance and the number of items, but because of the hashing process it's not actually O(1) either. Ah, I dunno. Well anyway, yeah a set will probably be faster in .NET, I wouldn't be able to say for sure without doing some performance tests. A generic list is plenty fast enough for this operation though. I've rarely ever seen a set used in .NET code.

It depends on your Set implementation and the Objects you put in the set. If, for example, you use a HashSet and you only add Objects which have unique hash values you will get O(1) 'contains' performance. 'Add' performance can also be O(1) if the Objects you add have unique hash values. Time to hash a String is negligible and the calculated value should be cached for the next time. Whether or not it's cached is implementation-specific, but in Java the hash for a String is cached after it's calculated the first time (which would happen on the 'Add' operation as you were loading from file). If you have collisions in the Set (multiple Objects have the same value) it does slow performance but unless the vast majority of the Objects hashed to the same value (which shouldn't happen with Strings) you wouldn't see a deterioration to O(n) performance, which is the default performance for 'contains' on the list.

edit: Wait, actually. I'm looking at this the wrong way. What I said above only matters if you're looking for what people say to be exactly what's in the swear filter, which obviously isn't feasible. What you want is whether or not a given String contains any of the words in the swear word list. I apologise, forgive me.
Quote from DarkTimes :I'm really not sure what your code is doing, but if I was going to make a swear filter, I'd do something like this.

Presuming you have a file called "swear.txt" in the same folder as your program's exe file that has a banned word on each line:

boobs
willy
knickers
thatcher

First of all I would load that file into memory when the programs starts, with some simple code like this:

// List to store swear words.
List<string> swearwords = new List<string>();

void LoadSwearWords()
{
// Get the path to the 'swear.txt' file.
string file = Path.Combine(Environment.CurrentDirectory, "swear.txt");

// Open text file for reading.
using (TextReader reader = new StreamReader(file))
{
// Loop through each line in the file.
string line;
while ((line = reader.ReadLine()) != null)
{
// Remove any whitespace and cast to lower case.
string word = line.Trim().ToLower();

// Add to list in memory.
this.swearwords.Add(word);
}
}
}

Once I had the list of swear words in memory, I would then need some code to check if a message contained a swear word.

bool MessageContainsSwearWord(string message)
{
// This regex splits words, trims whitespace and removes punctuation.
string[] words = Regex.Split(message, @"\W+");

// Loop through each word and check if it's a swear word.
foreach (string word in words)
{
if (this.swearwords.Contains(word.ToLower()))
{
return true;
}
}
return false;
}

The MessageContainsSwearWord method returns true if the message contains a swearword or false otherwise. You could use it like this:


string message = "This message contains the word boobs";

if (MessageContainsSwearWord(message))
{
Console.WriteLine("That message is filthy!");
}
else
{
Console.WriteLine("Aww, what a well-spoken boy.");
}

// OUTPUT: That message is filthy!

I hope that helps!

You can download my test project below (requires VS Express 2010).

Ok i'll try to use your codes..
I love how thatcher is a bad word
-
(DarkTimes) DELETED by DarkTimes
#9 - Woz
Quote from amp88 :.

Yes, anything that supports IEnumerable<T> is suitable as you have to enumerate the list looking if any of contained words in the text being validated.

Given that a Fixed array is best as cheapest memory footprint but List<T> cost is similar. Direct access of the words is not required.
-
(Stuff) DELETED by Stuff : tl;dr;
-
swear filter for C# (cmiller200) DELETED by franky500 : Spambot
-
(E.Reiljans) DELETED by E.Reiljans
#10 - Woz
Here is a very simple basic solution using C# and Linq and a test rig that is called with data that will fail and pass the filter.


<?php 
using System
;
using System.Linq;

namespace 
Scratch
{
    class 
Program
    
{
        static 
void Main(string[] args)
        {
            
string[] badWords = new string[] 
            { 
                
"fOrK"// case does not matter
                
"barstool"
                
"aerosol" 
            
};

            foreach (
string toTest in new string[]
                {
                    
"For Forks sake you Barstool.",
                    
"Should have no bad words."
                
})
            {
                
Console.WriteLine(CountBadWords(badWordstoTest).ToString() +
                    
" bad words found.");
            }
        }

        public static 
int CountBadWords(string[] badWordsstring toTest)
        {
            return 
badWords.Count(badWord => toTest.ToLower().Contains(badWord.ToLower()));
        }

        public static 
bool HasBadWords(string[] badWordsstring toTest)
        {
            return 
badWords.Any(badWord => toTest.ToLower().Contains(badWord.ToLower()));
        }
    }
}
?>

Yeah, I would use LINQ too, I just didn't in my example because I didn't know if skywatcher understood it and I didn't want to complicate the code unnecessarily.

I guess it's down to personal preference, but I would still use the regex to split the words, as otherwise you run into what I call the S****horpe problem. Edit: the LFS forum has this issue too it seems.

bool MessageContainsSwearWord(string message)
{
return Regex.Split(message, @"\W+").Any(w => swearwords.Contains(w.ToLower()));
}

As I say though it's down to personal preference whether you want to check only whole words or not. Of course it's not the most complete swear-filter ever, but it should work for most simple purposes.
Lol i'll try that soon but im busy getting to know the timers
#13 - Woz
Quote from DarkTimes :Yeah, I would use LINQ too, I just didn't in my example because I didn't know if skywatcher understood it and I didn't want to complicate the code unnecessarily.

I guess it's down to personal preference, but I would still use the regex to split the words, as otherwise you run into what I call the S****horpe problem. Edit: the LFS forum has this issue too it seems.

bool MessageContainsSwearWord(string message)
{
return Regex.Split(message, @"\W+").Any(w => swearwords.Contains(w.ToLower()));
}

As I say though it's down to personal preference whether you want to check only whole words or not. Of course it's not the most complete swear-filter ever, but it should work for most simple purposes.

I guess I avoid regex as it can cause maint issues if you have people in your team that do not understand. At least Linq is type safe to give that protection.

Like your solution though, nice and clean

FGED GREDG RDFGDR GSFDG