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

网友投稿 228 2023-07-24


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;

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Freemaker Replace函数的正则表达式运用
下一篇:Sublime Text 3常用插件及安装方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~