源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java统计字符串中指定元素出现次数方法

  • 时间:2020-04-28 06:06 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java统计字符串中指定元素出现次数方法
本文实例讲解了统计文本中某个字符串出现的次数或字符串中指定元素出现的次数方法,分享给大家供大家参考,具体内容如下 运行效果图: [img]http://files.jb51.net/file_images/article/201512/20151217142541980.jpg?20151117142610[/img] 程序查找的上此文件带"a"的字符在多少次 [img]http://files.jb51.net/file_images/article/201512/20151217142622408.jpg?20151117142631[/img] 具体代码如下
package com.zuidaima.util.string; 
import java.io.*; 
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统计字符串中指定元素出现次数方法,希望对大家的学习有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部