`
810364804
  • 浏览: 783751 次
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多

原文: java统计文本中某个字符串出现的次数源代码下载地址:http://www.zuidaima.com/share/1550463297014784.htm

统计文本中某个字符串出现的次数或字符串中指定元素出现的次数

文件样本:

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

程序查找的上此文件带"a"的字符在多少次

结果:

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


package com.zuidaima.util.string;
import java.io.*;
/**
* @author www.zuidaima.com
**/
public class CountString {
 
 public static int count(String filename, String target)
    throws FileNotFoundException, IOException {
   FileReader fr = new FileReader(filename);
   BufferedReader br = new BufferedReader(fr);
   StringBuilder strb = new StringBuilder();
   while (true) {
    String line = br.readLine();
    if (line == null) {
     break;
    }
    strb.append(line);
   }
   String result = strb.toString();
   int count = 0;
   int index = 0;
   while (true) {
    index = result.indexOf(target, index + 1);
    if (index > 0) {
     count++;
    } else {
     break;
    }
   }
   br.close();
   return count;
  }
 
 public static void main(String[] args) {
   try {
    System.out.println(count("D:\\zuidaima.txt", "a"));
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 
}


	    			

标签:java字符串统计个数文本话题:脚本和工具语言基础


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics