Here we introduce the countStringOccurrences method. This method receives two parameters. It returns the count of one string within another.
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"));
}
}
dog occurs: 2
dirt occurs: 0
bird occurs: 1
[ d] occurs: 2