如何在 Java 中的字符串数组中计算和打印重复的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11040397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:33:28  来源:igfitidea点击:

How can I count and print duplicate strings in a string array in Java?

java

提问by thecodefather

I have a dilemma on my hands. After much trial and error, I still could not figure out this simple task.

我手上有一个两难的问题。经过多次反复试验,我仍然无法弄清楚这个简单的任务。

I have one array

我有一个数组

String [] array = {anps, anps, anps, bbo, ehllo};

I need to be able to go through the array and find duplicates and print them on the same line. Words with no duplicates should be displayed alone

我需要能够遍历数组并找到重复项并将它们打印在同一行上。没有重复的词应该单独显示

The output needs to be like this

输出需要是这样的

anps anps anps
bbo
ehllo

I have tried while, for loops but the logic seems impossible.

我试过 while, for 循环,但逻辑似乎不可能。

采纳答案by javajavajava

Sort the array first then

先对数组进行排序,然后

for(int i = 0, i < array.length; i++){
    String temp = array[i];
    System.out.print(temp+" ");
    for(int j = i+1; j < array.length; j++){
        String temp2 = array[j];
        if(temp.compareTo(temp2) == 0){
            System.out.print(temp2+" ");
            i++;
        }
    }
    System.out.println();
}

or something similar...

或类似的东西...

回答by Hans Z

Okay, there are a worryingly number of either wrong answers or answers that use HashMapor HashSetfor this very simple iteration problem, so here is a correct solution.

好了,有一个令人担忧的数字或者错误的答案,或者答案是使用HashMapHashSet用于这个非常简单的迭代问题,所以这里是一个正确的解决方案。

Arrays.sort(array);

for (int i = 0; i < array.length; ++i){
    if (i+1 == array.length) {
        System.out.println(array[i]);
    } else if (array[i].equals(array[i+1])) {
        System.out.print(array[i]+" ");
    } else {
        System.out.println(array[i]);
    }
}

回答by GETah

There are multiple ways of achieving this.

有多种方法可以实现这一点。

  1. Use two for loops, one that loops through the array and picks a value and another inner loop where you go through the array (from the current index) looking for that value
  2. You could have a map that contains the words, you loop through the array and you fill out the map with the number of occurrences corresponding to the value currently fetched from the array
  1. 使用两个 for 循环,一个循环遍历数组并选择一个值,另一个内部循环在其中遍历数组(从当前索引)查找该值
  2. 你可以有一个包含单词的映射,你遍历数组并用与当前从数组中获取的值对应的出现次数填充映射

The second way is better. The code is something like:

第二种方式更好。代码是这样的:

Map<String, Integer> occurences = new HashMap<String, Integer>();
for(int index=0; index < array.length; index++){
       int nOcc = 1;
       if(occurences.containsKey(array[index]){
         nOcc = occurences.get(array[index]) + 1;
       }
       occurences.remove(array[index]);
       occurences.put(array[index], nOcc);
}

At this point, the map should contain all words (keys) and their corresponding number of occurrences (values)

此时,映射应包含所有单词(键)及其对应的出现次数(值)

回答by NominSim

If you sort the array first, then you can just check if the current index is equal to the next index (bearing in mind that you must account for IndexOutOfBounds), if they are equal do a System.out.print()if they are not equal do a System.Out.println().

如果您先对数组进行排序,那么您可以只检查当前索引是否等于下一个索引(请记住,您必须考虑IndexOutOfBounds),如果它们相等则执行 aSystem.out.print()如果它们不相等则执行 a System.Out.println()

String [] array = {"anps", "anps", "anps", "bbo", "ehllo"};
// If you already are assured that the strings in the array are sorted
// then the sort is not necessary. 
Arrays.sort(array);
for(int i = 0; i < array.length; i++){
    if((i+1)==array.length || !array[i].equals(array[(i+1)])){
        System.out.println(array[i]);
    } else {
        System.out.print(array[i]+" ");
    }
}

回答by Sergii Zagriichuk

Complexity n^2, just start from first value and go to the end finding the same, if you found print in one line and go to the new line, also you should delete all printed value.

复杂性n^2,只需从第一个值开始到最后发现相同,如果您在一行中找到打印并转到新行,您也应该删除所有打印的值。

Complexity nlogn + n== nlogn, mergeor quicksort, and after this go to the end and pring sequenced values. There are more solutions but I think its enough for you.

复杂nlogn + n== nlognmergequick排序,并在此之后走到底,普林测序值。有更多的解决方案,但我认为这对你来说已经足够了。

回答by Jean-Christophe Fortin

Naive Algorithms

朴素算法

  • Create a Map
  • Iterate through all array
  • check if key already exist in map
  • if yes update value +1
  • if no insert
  • print the map as you want
  • 创建地图
  • 遍历所有数组
  • 检查地图中是否已存在密钥
  • 如果是更新值+1
  • 如果没有插入
  • 根据需要打印地图

You should be able to do what you're looking for !

你应该能够做你正在寻找的东西!

回答by Anil Patile

Use below logic

使用以下逻辑

import java.util.ArrayList;


public class RepeatStringPrint {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String[] x = { "anps", "anps", "anps", "bbo", "ehllo" };
            String total[] = new String[50];
            String sTotal[] = null;
            for (int i = 0; i < x.length; i++) {
                total[i] = x[i];
            }
            for (int k = 0; k < total.length; k++) {
                int count = 0;
                if (total[k] != null) {
                    sTotal = new String[50];
                    for (int i = 0; i < total.length; i++) {
                        if (total[k] == total[i]) {
                            count++;
                            if (count <= 1) {
                                sTotal[i] = total[k];
                            }
                        }
                    }
                    if (sTotal[k] != null) {
                        for(int j=0; j<count; j++){
                            System.out.print(sTotal[k]+"\t");
                        }
                        System.out.print("\n");
                    }
                }

            }
        }
        catch (Exception e) {

        }
    }

}