欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-07-13 08:22:02|栏目:JAVA代码|点击:

本文实例讲解了统计文本中某个字符串出现的次数或字符串中指定元素出现的次数方法,分享给大家供大家参考,具体内容如下

运行效果图:

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

具体代码如下

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统计字符串中指定元素出现次数方法,希望对大家的学习有所帮助。

上一篇:Java实现将数字日期翻译成英文单词的工具类实例

栏    目:JAVA代码

下一篇:SpringBoot 多任务并行+线程池处理的实现

本文标题:java统计字符串中指定元素出现次数方法

本文地址:http://www.codeinn.net/misctech/156614.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有