java识别一篇文章中某单词出现个数的方法
程序员文章站
2024-03-06 10:32:31
本文实例讲述了java识别一篇文章中某单词出现个数的方法。分享给大家供大家参考。具体如下:
1. java代码:
import java.io.datainpu...
本文实例讲述了java识别一篇文章中某单词出现个数的方法。分享给大家供大家参考。具体如下:
1. java代码:
import java.io.datainputstream; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.ioexception; import java.util.stringtokenizer; import java.util.regex.matcher; import java.util.regex.pattern; public class select { public static void main(string[] args) { int num = 0; //定义:字节读取流 fileinputstream fis; try { //此处的路径需要根据具体情况来进行修改 fis = new fileinputstream("h:\\tankwar1.9\\src\\tank.java"); datainputstream dis = new datainputstream(fis); string line = null; while ((line = dis.readline()) != null) { //创建字符解析器 stringtokenizer st=new stringtokenizer(line,"!&(){}+-= ':;<> /"); while(st.hasmoretokens()) { string string=st.nexttoken(); if(string.equals("if")) { num++; } } ; } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } system.out.println(num); } }
2. select.java:
import java.io.datainputstream; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.ioexception; import java.util.stringtokenizer; import java.util.regex.matcher; import java.util.regex.pattern; public class select { public static void main(string[] args) { int num = 0; //定义:字节读取流 fileinputstream fis; try { fis = new fileinputstream("h:\\tankwar1.9\\src\\tank.java"); datainputstream dis = new datainputstream(fis); string line = null; while ((line = dis.readline()) != null) { //创建字符解析类 stringtokenizer st=new stringtokenizer(line,"!&(){}+-= ':;<> /"); while(st.hasmoretokens()) { string string=st.nexttoken(); if(string.equals("if")) { num++; } } ; } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } system.out.println(num); } }
3. stringtokenizerdemo.java:
import java.util.*; public class stringtokenizerdemo { public static void main(string[] args) { string str1 = "hello world!this is java code,stringtokenizer demo."; //声明并初始化字符串str1 string str2 = "how to use stringtokenizer?stringtokenizer?"; //声明并初始化字符串str2 stringtokenizer strt1 = new stringtokenizer(str1," ,.!"); //创建stringtokenizer类的对象strt1,并构造字符串str1的分析器 //以空格符、","、"."及"!"作为定界符 stringtokenizer strt2 = new stringtokenizer(str2," ?"); //创建stringtokenizer类的对象strt2,并构造字符串str2的分析器 //以空格符及"?"作为定界符 int num1 = strt1.counttokens(); //获取字符串str1中语言符号的个数 int num2 = strt2.counttokens(); //获取字符串str2中语言符号的个数 system.out.println("str1 has "+num1+" words.they are:"); while(strt1.hasmoretokens()) { //利用循环来获取字符串str1中下一个语言符号,并输出 string str = strt1.nexttoken(); system.out.print("\""+str+"\" "); } system.out.println("\nstr2 has "+num2+" words.they are:"); while(strt2.hasmoretokens()) { //利用循环来获取字符串str2中下一个语言符号,并输出 string str = strt2.nexttoken(); system.out.print("\""+str+"\" "); } } }
希望本文所述对大家的java程序设计有所帮助。
上一篇: asp.net的cms 原理篇