This article explains the method of counting the number of times a string appears in the text or the number of times a specified element appears in the string. It is shared with you for your reference. The specific content is as follows
Running renderings:
How many times does the program look for characters with "a" on this file?
The specific code is as follows
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(); } } }The above is the method of stating the number of occurrences of elements in Java strings. I hope it will be helpful to everyone's learning.