一.统计段落中出现某个词的次数
public static int word(String str, String card) {
int count = 0, index = 0;
while ((index = str.indexOf(card, index)) != -1) {
index = index + card.length();
count++;
}
return count;
}
indexOf函数可以直接在字符串中查找需要的字符或字符串,不论字符串的大小
二、编写敏感词过滤程序
说明:在网络程序中,如聊天室、聊天软件等,经常需要对一些用户所提交的聊天内容中的敏感性词语进行过滤。
如“性”、“色情”、“爆炸”、“恐怖”、“枪”、“军火”等,这些都不可以在网上进行传播,需要过滤掉或者用其他词语替换掉。
public static void main(String[] args) {
Scanner c = new Scanner(System.in);
System.out.println("请输入聊天内容:");
String str = c.nextLine();
//StringBuilder str1 = new StringBuilder(str);
String ch[] = { "色情", "爆炸", "恐怖", "枪", "军火" };
for (String s : ch) {
str = str.replaceAll(s, "*");
}
System.out.println("聊天内容:" + str);
}
注意事项,在使用函数是尽量不要单独使用,令函数的结果等于一个变量。这样可以避免程序执行该函数后不显示执行结果。