This article describes the method of Java stating the number of occurrences of a string on another string. Share it for your reference, as follows:
Java counts the number of times a string appears in another string
The code is as follows:
package me.chunsheng.javatest;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * Created by wei_spring on 16/10/11. * <p> * Statistics the number of times a string appears in another string* A method of regular matching, assuming that the string is not a special string* eg:finder("adadadadauada", "ada") will be inaccurate. * Another traversal solves the above situation. * The time between the two is as follows (in nanoseconds): regular is obviously time-consuming, and regular is not used for statistics!!! * finder:3 * finderTime:1579549 * getCount:4 * getCountTime:34506 */public class SubStringCount { public static void main(String[] args) { System.out.println("Wulin.com test result:"); long current1 = System.nanoTime(); System.out.println("finder:" + finder("adadadadauada", "ada")); System.out.println("finderTime:" + (System.nanoTime() - current1)); long current2 = System.nanoTime(); System.out.println("getCount:" + getCount("adadadadauauda", "ada")); System.out.println("getCountTime:" + (System.nanoTime() - current2)); } public static int getCount(String source, String sub) { int count = 0; int length = source.length() - sub.length(); for (int i = 0; i < length; i++) { String sourceBak = source.substring(i, i + sub.length()); int index = sourceBak.indexOf(sub); if (index != -1) { count++; } } return count; } public static int finder(String source, String regexStr) { String regex = "[a-zA-Z]+"; if (regexStr != null && !regexStr.equals("")) { regex = regexStr; } Pattern expression = Pattern.compile(regex); Matcher matcher = expression.matcher(source); int n = 0; while (matcher.find()) { n++; } return n; }}Running results:
Always have a pious heart and are willing to share. Knowledge is more meaningful.
PS: Here are two very convenient statistical tools for your reference:
Online word count tool:
http://tools.VeVB.COM/code/zishutongji
Online character statistics and editing tools:
http://tools.VeVB.COM/code/char_tongji
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.