背景
我有一个文本字符串和一个哈希集,其中包含我正在查找的单词。
给定的
String doc = "one of the car and bike and one of those";
String [] testDoc = doc.split("\\s+");
HashSet<String> setW = new HashSet<>();
setW.add("and");
setW.add("of");
setW.add("one");
目标
我们的目标是扫描字符串,每次我们遇到散列集中的单词时,我们都要存储该单词和起始索引的位置。
在上面的情况下,我们应该能够存储以下内容
one-->0
of-->4
and-->15
and-->24,
one-->28,
of-->32
`尝试
//create hashmap
for(int i = 0; i<testDoc.length; i++){
if(setW.contains(testDoc[i])) {
doc.indexOf(testDoc[i]);
//add string and its index to hashmap
}
到目前为止,这就是我所想到的,唯一的问题是indexOf方法只查看第一次出现的单词,所以我不确定该怎么做。如果我在扫描完每个单词后不断修剪字符串,那么我将不会获得原始字符串中单词的索引位置。
我想在这里提供一些意见。
https://stackoverflow.com/questions/56469180
复制相似问题