当前位置: 移动技术网 > IT编程>开发语言>Java > java统计字符串中指定元素出现次数方法

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

运行效果图:

程序查找的上此文件带"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统计字符串中指定元素出现次数方法,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网