Hey,
I came across the task to find all occurences of a substring in another string and was wondering what will be the best algorithm to solve this problem.
For demonstration purposes I used the string "The cat sat on the mat" and search for all occurences of the substring "at". This should ultimately result in an occurence count of 3. Since I'm programming in java at the moment the first thing that popped into my mind was this:
public static void main(String[] args) {
int count=0;
String s = "The cat sat on the mat";
Pattern pattern = Pattern.compile("at");
Matcher matcher = pattern.matcher(s);
while(matcher.find()){
count++;
}
System.out.println("Pattern: "+pattern+" Count: "+count);
}
Somehow I doubt that this is the optimal solution for this problem. So if someone knows how an optimal (or at least pretty good) solution should look ... please answer! You can post your answer in any language not necessarily java (altough that would be great :)).
Thanks a lot!