In response to a recent SO question, I answered with the following code, and was wondering if anyone had any input on it. I'm always looking for an opprotunity to learn!
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class WordFinder {
public static void main(String[] args) {
String phrase = "0123hello9012hello8901hello7890";
String[] words = { "hello", "90" };
Map<String, Stack<Integer>> dest = findWordsInString(words, phrase);
System.out.println(dest.toString());
}
public static Map<String, Stack<Integer>> findWordsInString(String[] words, String phrase) {
Map<String, Stack<Integer>> dest = new HashMap<>();
for (String word : words) {
Stack<Integer> locations = new Stack<>();
for (int loc = -1; (loc = phrase.indexOf(word, loc + 1)) != -1;) {
locations.add(loc);
}
dest.put(word, locations);
}
return dest;
}
}
Program Output:
{90=[9, 19, 29], hello=[4, 13, 22]}