http://www.360coding.com/html/ASP.NET/24071.html

 using System; 
  
using System.Collections.Generic; 
  
using System.Text; 
  
using System.Text.RegularExpressions; 
  
using System.IO; 
  
using System.Collections; 
   
  
namespace filter 
  { 
   
class Filter 
   { 
   
private Hashtable h = new Hashtable(); 
   
   
public Filter() 
   { 
   
   } 
   
   
public void Inital(string filename) 
   { 
   
string[] strs = GetBadwords(filename); 
   
foreach (string str in strs) 
   { 
   AddBadword(str); 
   } 
   } 
   
   
private void AddBadword(string str) 
   { 
   
char c = str[0]; 
   
if (h.ContainsKey(c)) 
   { 
   TreeNode node 
= (TreeNode)h[c]; 
   AddNode(node, str, 
1); 
   } 
   
else 
   { 
   TreeNode node 
= new TreeNode(); 
   node.Text 
= c; 
   
if (str.Length == 1
   node.Leaf 
= true
   
else 
   node.Leaf 
= false
   
   h.Add(c, node); 
   AddNode(node, str, 
1); 
   } 
   } 
   
   
private void AddNode(TreeNode node, string str, int p) 
   { 
   
if (str.Length > p) 
   { 
   
if (node.ChildNodes == null
   node.ChildNodes 
= new Hashtable(); 
   
   TreeNode n; 
   
if (!node.ChildNodes.ContainsKey(str[p])) 
   { 
   n 
= new TreeNode(); 
   n.Text 
= str[p]; 
   
if (str.Length == p + 1
   n.Leaf 
= true
   
else 
   n.Leaf 
= false
   
   node.ChildNodes.Add(str[p], n); 
   } 
   
else 
   n 
= (TreeNode)node.ChildNodes[str[p]]; 
   
   AddNode(n, str, p 
+ 1); 
   } 
   
   } 
   
public bool Pass(string str) 
   { 
   
int total, current; 
   total 
= str.Length; 
   
for (current = 0; current < total; current++
   { 
   
if (h.ContainsKey(str[current])) 
   { 
   TreeNode node 
= (TreeNode)h[str[current]]; 
   
if (containChar(node, str, current + 1,total)) 
   
return false
   } 
   } 
   
return true
   } 
   
   
private bool containChar(TreeNode node, string str, int p,int total) 
   { 
   
   
if (node.Leaf == true
   
return true
   
   
if (p >= total) 
   
return false
   
   
if (node.ChildNodes.ContainsKey(str[p])) 
   { 
   TreeNode n 
= (TreeNode)node.ChildNodes[str[p]]; 
   
return containChar(n, str, p + 1, total); 
   } 
   
else 
   
return false
   
   } 
   
   
private string[] GetBadwords(string filename) 
   { 
   List
<string> list = new List<string>(); 
   
using (StreamReader sr = new StreamReader(filename, Encoding.Default)) 
   { 
   
string str = sr.ReadToEnd(); 
   MatchCollection mc 
= Regex.Matches(str, @"\S+"); 
   
foreach (Match m in mc) 
   { 
   Console.WriteLine(m.Value); 
   list.Add(m.Value); 
   } 
   } 
   
return list.ToArray(); 
   } 
   } 
  } 

相关文章: