本文執行個體講解了統計文本中某個字串出現的次數或字串中指定元素出現的次數方法,分享給大家供大家參考,具體內容如下
運行效果圖:
程式尋找的上此檔案帶"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統計字串中指定元素出現次數方法,希望對大家的學習有所協助。