Finding repeated words on a string and counting the repetitions

后端 未结 29 885
梦谈多话
梦谈多话 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:06

    please try these it may be help for you.

    public static void main(String[] args) {
            String str1="House, House, House, Dog, Dog, Dog, Dog";
            String str2=str1.replace(",", "");
            Map map=findFrquenciesInString(str2);
            Set keys=map.keySet();
            Collection vals=map.values();
            System.out.println(keys);
            System.out.println(vals);
        }
    
    private static Map findFrquenciesInString(String str1) {
            String[] strArr=str1.split(" ");
            Map map=new HashMap<>();
            for(int i=0;i1 && strArr[i]!="-1") {
                    map.put(strArr[i], count);
                    strArr[i]="-1";
                }
            }
            return map;
        }
    

提交回复
热议问题