統計一段文章中每個單詞出現的次數,
this is a book this is an elephont
也可以只統計指定單詞
1 import java.util.Collection;
2 import java.util.HashMap; 3 import java.util.Map; 4 import java.util.Map.Entry; 5 6 public class TestDay19_2 { 7 8 public static void main(String[] args) { 9 10 String s = "As a student, we have study for many years. " + "During there years, we study Chinese, English, " 11 + "science and so on. In this period, with the improvement of our knowledge," 12 + "we not only read the books in class but also read extracurricular after school. " 13 + "In my opinion Dream of the red chamber is the best book I have read. " 14 + "In this book, the great author Cao xueqin his view about love. " 15 + "He had firmly faith in what is the true love and try to tell us " 16 + "that there are different kinds of love, " 17 + "only one kind which should be considered as True Love. In a dream, " 18 + "and under mythical circumstances, the main character of the novel, " 19 + "Jia baoyu, met the Fairy Disenchantment in the Land of Illusions. " 20 + "She showed him three registers each containing the names " 21 + "and the happenings in life of 12 girls in his clan. " 22 + "Each girl represents a kind of love. From the stories " + "which are unfolding in the novel, " 23 + "the reader should know the characteristics of the different kinds of love, " 24 + "and should be able to distinguish True Love from the other kinds. " 25 + "True love is acceptance, committal, mutual and without any post conditions. " 26 + "The love between Lin daiyu and Jia baoyu is considered to be True Love. " 27 + "Just saying or hearing I love you is not good enough because talk is cheap. " 28 + "Action in mutual commitment is essential, as we can see in the novel. " 29 + "We always have dreams. What's ours dream? Do you know what you exactly want? " 30 + "And do you work hard for it. In this book, " 31 + "you can taste the feeling of the author about his strong will. In his words, " 32 + "you can find the charm of Chinese. It is not a book, but a precious deposits. " 33 + "You can get a lot from it. But unfortunately, " 34 + "the novel was never completed to such a state. On the other hand, maybe, " 35 + "it is another kind of beauty of the book. If you have not read this book yet, " 36 + "just go and read it. You will love it. "; 37 String[] ss = s.split(" "); 38 39 HashMap<String, Integer> hm = new HashMap<>(); 40 // 指定想要統計的單詞 41 hm.put("this", 0); 42 hm.put("is", 0); 43 hm.put("a", 0); 44 hm.put("book", 0); 45 hm.put("an", 0); 46 47 for (int i = 0; i < ss.length; i++) { 48 String word = ss[i]; 49 if (hm.containsKey(word)) { 50 hm.put(word, hm.get(word) + 1); 51 } 52 // 把下面這三行放開就是統計每個單詞的次數 53 // else{ 54 // hm.put(ss[i], 1); 55 // } 56 } 57 58 Collection<Map.Entry<String, Integer>> c = hm.entrySet(); 59 for (Entry<String, Integer> entry : c) { 60 System.out.println(entry.getKey() + "出現了" + entry.getValue() + "次"); 61 } 62 } 63 }