手机
当前位置:查字典教程网 >编程开发 >Java >java统计字符串中指定元素出现次数方法
java统计字符串中指定元素出现次数方法
摘要:本文实例讲解了统计文本中某个字符串出现的次数或字符串中指定元素出现的次数方法,分享给大家供大家参考,具体内容如下运行效果图:程序查找的上此文...

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

运行效果图:

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

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

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

具体代码如下

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中计算字符串长度的方法及u4E00与u9FBB的认识

java unicode转码为中文实例

Java中ArrayList类的使用方法

java自定义注解接口实现方案

java 字符串相减(很简单的一个方法)

java中删除数组中重复元素方法探讨

java 删除数组元素与删除重复数组元素的代码

java字符串的合并

java生成申请单序列号的实现方法

Java中去除字符串中所有空格的几种方法

精品推荐
分类导航