java统计字符串中指定元素出现次数方法
作者:yaerfeng 时间:2022-11-02 16:05:40
本文实例讲解了统计文本中某个字符串出现的次数或字符串中指定元素出现的次数方法,分享给大家供大家参考,具体内容如下
运行效果图:
程序查找的上此文件带"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,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java class文件格式之常量池_动力节点Java学院整理
2023-04-14 07:14:06
![](https://img.aspxhome.com/file/2023/2/66472_0s.jpg)
struts2自定义拦截器的示例代码
2021-12-01 16:24:52
![](https://img.aspxhome.com/file/2023/3/78243_0s.jpg)
C#字符集编码的使用及说明
2023-12-05 02:06:05
![](https://img.aspxhome.com/file/2023/3/78113_0s.png)
详解使用Spring Security OAuth 实现OAuth 2.0 授权
2023-10-01 23:05:10
![](https://img.aspxhome.com/file/2023/9/72279_0s.png)
SpringMVC中使用@PathVariable绑定路由中的数组的方法
2023-11-27 14:21:01
![](https://img.aspxhome.com/file/2023/9/61289_0s.png)
Mybatis实现Mapper动态代理方式详解
2023-08-13 08:37:41
通过Java实现在Word中创建可填充表单
2023-08-05 21:11:40
![](https://img.aspxhome.com/file/2023/4/58034_0s.jpg)
SpringBoot2 整合Ehcache组件,轻量级缓存管理的原理解析
2022-02-07 22:04:34
Swagger2匹配多个controller代码实例
2022-07-31 03:42:24
Spring Aop 如何获取参数名参数值
2022-09-08 17:00:41
elasticsearch节点的transport请求发送处理分析
2022-04-05 22:38:08
mybatis-plus 返回部分字段的解决方式
2023-03-25 14:45:04
![](https://img.aspxhome.com/file/2023/1/61281_0s.jpg)
Java中checkbox实现跨页多选的方法
2023-10-14 11:01:20
Spring Boot产生环形注入的解决方案
2023-11-08 20:14:04
详解Java双轴快速排序算法
2023-10-05 15:50:14
![](https://img.aspxhome.com/file/2023/6/69316_0s.jpg)
解决mybatis-plus自动配置的mapper.xml与java接口映射问题
2023-08-25 04:16:02
![](https://img.aspxhome.com/file/2023/5/58045_0s.gif)
Spring Boot高级教程之使用Redis实现session共享
2022-10-20 09:59:01
java中动态 代理的实现
2023-11-17 16:16:25
Android利用传感器实现微信摇一摇功能
2023-07-12 05:05:18
java如何获得redis所有的key-value
2022-03-13 12:22:14
![](https://img.aspxhome.com/file/2023/3/60823_0s.jpg)