count
Category: Programming
Author: Stuart Reges
Book Chapter: 4.3
Problem: count
Write a static method called count that takes as
parameters a target string and a source string and that returns a count of
the number of occurrences of the target string in the source string. For
example, the following call:
count("i", "Mississippi")
should return 4 because there are 4 occurrences of the string "i" in the
string "Mississippi". Your method should ignore case when comparing
strings. For example, the call:
count("iss", "MISSISSIPPI")
should return 2 because there are two occurrences of "iss" in
"MISSISSIPPI". Your method should consider all possible starting positions
for the target string. For example, given the following call:
count("EE", "EeEeE")
Your method should return the value 4 because there are 4 different
locations where the string "ee" occurs in the string "EeEeE" (starting at
index 0, index 1, index 2, and index 3).
You may assume that the target string is not empty. Recall that the String
class has the following useful methods:
charAt(index) character at a specific index
endsWith(text) whether or not the string ends with some text
equals(text) whether or not the string equals given text
equalsIgnoreCase(text) whether or not the string equals given text
ignoring case
indexOf(text) index of a particular string (-1 if not found)
length() number of characters in the string
startsWith(text) whether or not string starts with some text
substring(start, stop) characters from start index (inclusive) to
stop index (exclusive)
substring(start) characters from start index (inclusive) to end
of string
toLowerCase() a new string with all lowercase letters
toUpperCase() a new string with all uppercase letters