栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150815.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号