Finding repeated words on a string and counting the repetitions

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

    package string;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class DublicatewordinanArray {
    public static void main(String[] args) {
    String str = "This is Dileep Dileep Kumar Verma Verma";
    DuplicateString(str);
        }
    public static void DuplicateString(String str) {
    String word[] = str.split(" ");
    Map < String, Integer > map = new HashMap < String, Integer > ();
    for (String w: word)
    if (!map.containsKey(w)) {
    map.put(w, 1);
        }
    else {
    map.put(w, map.get(w) + 1);
            }
    Set < Map.Entry < String, Integer >> entrySet = map.entrySet();
     for (Map.Entry < String, Integer > entry: entrySet)
    if (entry.getValue() > 1) {
     System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
    }
     }
    }
    

提交回复
热议问题