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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

yaerfeng   2021-03-20 我要评论
想了解java统计字符串中指定元素出现次数方法的相关内容吗,yaerfeng在本文为您仔细讲解java统计字符串中指定元素出现次数的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java字符串出现次数,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统计字符串中指定元素出现次数方法,希望对大家的学习有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们