C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument 1: This is the source string we want to search within. We name this argument "text."
Argument 2: This is the string we want to find—the pattern within the first string. We name this argument "pattern."
Main: Here we test the countStringOccurrences method. We can check the results with a sample string.
Java program that counts string occurrences
public class Program {
public static int countStringOccurrences(String text, String pattern) {
int count = 0;
int i = 0;
// Keep calling indexOf for the pattern.
while ((i = text.indexOf(pattern, i)) != -1) {
// Advance starting index.
i += pattern.length();
// Increment count.
count++;
}
return count;
}
public static void main(String[] args) {
String value = "cat dog dog bird";
// Test method on these strings.
int count = countStringOccurrences(value, "dog");
System.out.println("dog occurs: " + count);
System.out.println("dirt occurs: "
+ countStringOccurrences(value, "dirt"));
System.out.println("bird occurs: "
+ countStringOccurrences(value, "bird"));
System.out.println("[ d] occurs: "
+ countStringOccurrences(value, " d"));
}
}
Output
dog occurs: 2
dirt occurs: 0
bird occurs: 1
[ d] occurs: 2
And: This step reduces unnecessary searching. It also means overlapping patterns are skipped.
Caution: To find overlapping patterns within the source string, please change the method to increment "i" by 1.