【问题标题】:Counting duplicate strings in array with equals()用equals()计算数组中的重复字符串
【发布时间】:2016-02-06 04:11:49
【问题描述】:

Java 新手,我似乎无法弄清楚:

我要做的就是打印一个重复的字符串以及它在数组中出现的次数(不使用哈希表或类似的东西,只是非常简单)。

假设这样的数组:

tempArray = {"dogs", "cats", "dogs", "dogs", "mice", "snakes", "cats"}

到目前为止,这是我的代码:

int flowerCount = 0;
for (int j = 0; j < tempArray.length - 1; j++) {
        for (int k = j + 1; k < tempArray.length; k++) {
              if( (tempArray[j].equals(tempArray[k])) && (j != k) ) {
                    System.out.println(tempArray[j]);
                    flowerCount++;
               }

         }

 }

显然这不起作用,我在这里做错了什么?这看起来应该很简单,但我无法正确地获得嵌套循环和计数器。

【问题讨论】:

  • 为什么它显然不起作用?预期输出是多少,实际输出是多少?
  • 正如我所说,预期的输出是“打印一个重复的字符串及其在数组中出现的次数”。它目前所做的只是将重复的项目打印错误的次数
  • 您是在寻找函数运行前已知的特定字符串,还是试图找出所有重复的字符串?那么,在您的示例中,您的输出应该是“dogs”*3、“cats”*2 吗?
  • 你有一个一维数组。拥有内部 for 循环会使事情变得过于复杂。
  • 我只是对数组进行排序并寻找相等的连续元素。

标签: java arrays string nested-loops


【解决方案1】:

您可以使用Arrays.sort 对数组进行排序。这将使相同的元素彼此相邻。然后,您可以简单地使用 while 循环遍历列表,查找相等的连续元素。

int i = 0;
while (i < arr.length) {
  int start = i;
  while (i < arr.length && arr[i].equals(arr[start])) {
    ++i;
  }
  int count = i - start;
  System.out.println(arr[start] + " " + count);
}

【讨论】:

  • 您可以只使用一个循环并在元素更改时打印上一个。
【解决方案2】:

计算重复项的一种简单方法是尝试将它们添加到集合中。一个集合不允许重复,所以每次添加字符串失败,都是因为该字符串已经存在于集合中。

集合中的add() 方法返回一个布尔值,指示添加是否成功。如果您尝试添加的字符串已经在集合中,则添加将失败并且该方法将返回 false。

比如:

HashSet<String> yourSet = new HashSet<>(); //Could be any kind of set, I'm just used to HashSets
int j = 0; j < tempArray.length - 1; j++) {
    if (yourSet.add(tempArray[j]) {
        //String was added succesfully, so it is not a duplicate.
    }  else {
        //String is duplicate.  Increment a duplicate counter for this string (and start at 2, if you want to include the initial occurence that is already in the set
    }
}

【讨论】:

    【解决方案3】:

    带有数组和用于

    String printed = "";
        for(String auxOne : tempArray){
            int CountRepeat = 0;
            for(String auxTwo : tempArray){
                if(auxOne.equals(auxTwo)){
                    CountRepeat++;
                }
            }
            if(CountRepeat>1 && (printed.indexOf(auxOne)==-1)){
                printed += auxOne;
                System.out.println(auxOne + " : " + CountRepeat);
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 2011-11-05
      • 2012-08-11
      • 2017-07-09
      • 2021-02-02
      • 2021-06-29
      • 1970-01-01
      • 2017-09-03
      • 2016-05-20
      相关资源
      最近更新 更多