How to count the occurrences of a Sub String in another String?

How to count the occurrences of a Sub String in the given String > String search

Problem Statements:

  1. I have a long String, I want to find out the occurrence of sub string in this.
  2. How to find out a duplicate sub string in a long String.
  3. I want to print multiple occurrence count of sub String.
 Source Code:
 package com;  
 import org.springframework.util.StringUtils;

public class Test {
	/**
	 * @param args
	 */
	public static void main(String args[]) {

		String str = "Java Technology J2EE Technology JSP Technology Servlet Technology Spring Technology Hibernate Technology Jboss Technology"; // count

		System.out.println("Count By Using Spring Framework:: \n"
				+ StringUtils.countOccurrencesOf(str, "Technology"));

		System.out.println("Count By Using Apache String Util Class:: \n"
				+ org.apache.commons.lang.StringUtils.countMatches(str,
						"Technology"));

		System.out.println("Count By Using While Loop:: \n"
				+ CharCount(str, "Technology"));

	}

	public static int CharCount(String str, String searchStr) {
		int occurence = 0;
		int count = 0;

		while ((count = str.indexOf(searchStr, count)) != -1) {
			count++;
			occurence++;
		}

		return occurence;
	}

}







Output:

Count By Using Spring Framework 
7
Count By Using Apache String Util Class 
7
Count By Using While Loop 
7

10article.com Tutorials

10article.com Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *