编写敏感词过滤程序
在网络程序中,如聊天室、聊天软件等,经常需要对一些用户所提交的聊天内容中的敏感性词语进行过滤。如“性”、“色情”、“爆炸”、“恐怖”、“枪”等,这些都不可以在网上进行传播,需要过滤掉或者用其他词语替换掉。
思路:将用户的聊天内容保存到一个字符串对象或一个StringBuilder对象中,然后与敏感词语进行比对。如果属于敏感词语,就过滤掉或替换掉。
import java.util.Scanner;
public class Mesc {
public static void main(String[] args) {
String []words={"性","色情","爆炸","恐怖","枪"};
//获取用户键盘输入的内容
Scanner scanner=new Scanner(System.in);
System.out.println("尽情的说吧");
String message=scanner.next();
//让数组中的元素一个一个进行比较
for(int i=0;i<words.length;++i){
message=message.replace(words[i],"***");
}
System.out.println(message);
}
}
运行结果