【发布时间】:2019-09-16 00:30:34
【问题描述】:
我有一个字符串[],我想循环遍历以获取每个单词出现在目标列表中时的索引。
我知道 target.indexOf(word) 将返回一个单词第一次出现的索引,但是如果同一个单词在目标列表中出现多次怎么办?如何获取每个出现的索引以及所有其他单词的索引并将索引存储在数组中以供以后使用?
String[] words = ["this", "test"];
List<String> targetList = Arrays.asList("this", "test", "is", "a", "complicated", "test");
ArrayList<Integer> indexList = new ArrayList<Integer>();
for (String word : words) {
int index = targetList.indexOf(word);
if (index != -1) {
indexList.add(index);
}
}
【问题讨论】:
-
因此,在此示例中,“test”一词在 targetList 中出现了两次,我想确保在循环遍历单词列表时,我并不总是得到第一个“test”的出现会期望 indexList 的值是 [0,1,5]。
-
马克,很抱歉造成混乱。我没有剪切和粘贴我的代码,所以我在打字时遗漏了一些东西。它是 java,我已经进行了编辑。