java统计字符串中指定元素出现次数方法
更新时间:2015年12月17日 14:29:21 作者:yaerfeng
这篇文章主要介绍了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统计字符串中指定元素出现次数方法,希望对大家的学习有所帮助。
相关文章
关于MyBatis 查询数据时属性中多对一的问题(多条数据对应一条数据)
这篇文章主要介绍了MyBatis 查询数据时属性中多对一的问题(多条数据对应一条数据),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-01-01
SpringBoot中Elasticsearch的连接配置原理与使用详解
Elasticsearch是一种开源的分布式搜索和数据分析引擎,它可用于全文搜索、结构化搜索、分析等应用场景,本文主要介绍了SpringBoot中Elasticsearch的连接配置原理与使用详解,感兴趣的可以了解一下2023-09-09
java对象序列化与反序列化的默认格式和json格式使用示例
这篇文章主要介绍了java对象序列化与反序列化的默认格式和json格式使用示例,需要的朋友可以参考下2014-02-02


最新评论