Finding repeated words on a string and counting the repetitions

后端 未结 29 937
梦谈多话
梦谈多话 2021-02-05 17:49

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = \"House, House         


        
29条回答
  •  终归单人心
    2021-02-05 18:20

    If you pass a String argument it will count the repetition of each word

    /**
     * @param string
     * @return map which contain the word and value as the no of repatation
     */
    public Map findDuplicateString(String str) {
        String[] stringArrays = str.split(" ");
        Map map = new HashMap();
        Set words = new HashSet(Arrays.asList(stringArrays));
        int count = 0;
        for (String word : words) {
            for (String temp : stringArrays) {
                if (word.equals(temp)) {
                    ++count;
                }
            }
            map.put(word, count);
            count = 0;
        }
    
        return map;
    
    }
    

    output:

     Word1=2, word2=4, word2=1,. . .
    

提交回复
热议问题