加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

java统计文本中某个字符串出现的次数

(2016-08-10 06:43:39)
标签:

java

分类: JAVA




public class Test {
// 统计数字或者字符出现的次数
public static TreeMap Pross(String str) {
char[] charArray str.toCharArray();

TreeMap tm new TreeMap();

for (int 0; charArray.length; x++) {
if (!tm.containsKey(charArray[x])) {
tm.put(charArray[x], 1);
else {
int count tm.get(charArray[x]) 1;
tm.put(charArray[x], count);
}
}
return tm;
}

public static void main(String[] args) {
BufferedReader br null;
int line 0;
String str "";
StringBuffer sb  new StringBuffer();
try {
br new BufferedReader(new FileReader("c:\\1.txt"));
while ((str br.readLine()) != null) {
sb.append(str);
++line;
}
System.out.println("\n文件行数: line);
System.out.println("\n文件内容: sb.toString());
TreeMap tm Pross(sb.toString());
System.out.println("\n字符统计结果为:" tm);
catch (FileNotFoundException e) {
e.printStackTrace();
catch (IOException e) {
e.printStackTrace();
finally {
if (br != null) {
try {
br.close();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}





  1. public static int count(String filename, String target)  
  2.     throws FileNotFoundException, IOException  
  3.    FileReader fr new FileReader(filename);  
  4.    BufferedReader br new BufferedReader(fr);  
  5.    StringBuilder strb new StringBuilder();  
  6.    while (true 
  7.     String line br.readLine();  
  8.     if (line == null 
  9.      break 
  10.      
  11.     strb.append(line);  
  12.     
  13.    String result strb.toString();  
  14.    int count 0 
  15.    int index 0 
  16.    while (true 
  17.     index result.indexOf(target, index 1);  
  18.     if (index 0 
  19.      count++;  
  20.     else  
  21.      break 
  22.      
  23.     
  24.    br.close();  
  25.    return count;  
  26.    
  27.    
  28.  public static void main(String[] args)  
  29.    try  
  30.     System.out.println(count("D:\\zuidaima.txt""a"));  
  31.    catch (FileNotFoundException e)  
  32.     e.printStackTrace();  
  33.    catch (IOException e)  
  34.     e.printStackTrace();  
  35.     
  36.    
  37.    

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有