【问题标题】:How to grab the indexes of a word that appears more than once in a list of Strings如何获取在字符串列表中多次出现的单词的索引
【发布时间】: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,我已经进行了编辑。

标签: java list iterator


【解决方案1】:

我假设您想编写 java.util.您需要使用列表数组来存储每次出现的单词。

    String[] words = {"this", "test"};
    String[] targetList = {"this", "test", "is", "a", "complicated", "test"};
    ArrayList<Integer> indexList[] = new ArrayList[words.length];

    for(int i=0;i<words.length;i++)
        indexList[i] = new ArrayList<Integer>();

    for(int i=0;i<words.length;i++)
    {
        String current = words[i];
        for(int j=0;j<targetList.length;j++)
        {
            if(words[i].equals(targetList[j]))
            {
                indexList[i].add(j);
            }
        }
    }

【讨论】:

  • 警告:您使用的是原始类型:new ArrayList[words.length]。永远不要在新代码中使用它们。
  • @AndrewTobilko 这是一个 ArrayLists 数组(除非类型是原始的,否则无法完成)。换句话说,这是一个质量很差的响应,不建议使用。
猜你喜欢
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 2021-05-03
  • 1970-01-01
  • 2016-06-16
相关资源
最近更新 更多