Program to find the number of occurrences in a given String

Problem Statement: Given 2 String source and target, find the number of occurrences that the String target is present in String source and return the count.



Test Cases:

Test Case – 1
Input:  My java program jav java i like java course, java
Output:  3
Test Case – 2
Input:  aabraakaadaabraa, aa
Output:  5



Java Source Code
public static void main(String[] args) {
		System.out.println(countOccurences("My java program jav java. i like java course", "java"));
        System.out.println(countOccurences("aabraakaadaabraa", "aa"));
	}
	
	public static int countOccurences(String sentence, String word) {
		int count = 0;
		int index = 0;
		int length = word.length();
		while(index != -1) {
			index = sentence.indexOf(word, index);
			
			if(index != -1) {
				count++;
				index = index + length;
			}
		}
		return count;
	}



About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

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