Finding repeated words on a string and counting the repetitions

后端 未结 29 953
梦谈多话
梦谈多话 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条回答
  •  旧时难觅i
    2021-02-05 18:11

    import java.util.HashMap;
    import java.util.LinkedHashMap;
    
    public class CountRepeatedWords {
    
        public static void main(String[] args) {
              countRepeatedWords("Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.");
        }
    
        public static void countRepeatedWords(String wordToFind) {
            String[] words = wordToFind.split(" ");
            HashMap wordMap = new LinkedHashMap();
    
            for (String word : words) {
                wordMap.put(word,
                    (wordMap.get(word) == null ? 1 : (wordMap.get(word) + 1)));
            }
    
                System.out.println(wordMap);
        }
    
    }
    

提交回复
热议问题