java-統計一段句子中各單詞出現的次數


  1. 問題:統計一段句子中各單詞出現的次數。
  2. 思路:
  3. 1、使用split方法將文章進行分割,我們這里以空格、逗號和句點為分隔符,然后存到一個字符串數組中。
  4. 2、創建一個hashMap集合,key是字符串類型,保存單詞;value是數字類型,保存該單詞出現的次數。
  5. 3、遍歷思路1中的字符串數組,如果key(單詞)沒有出現過,map中增加一個元素,key為該單詞,定義value為1;如果key(單詞)出現過,那么value的值加1。
  6. 4.遍歷輸入key及其對應的value值。
  7. 具體代碼如下:
  8. StrList類,實現統計單詞出現次數的方法。
  9. package wordCounts;
  10. import java.util.HashMap;
  11. import java.util.Map.Entry;
  12. public class StrList {
  13. public String StatList(String s) {
  14. StringBuffer sb = new StringBuffer();
  15. HashMap<String, Integer> has = new HashMap<String,Integer>();//打開哈希表,字符類型儲存key(單詞),整型儲存value(單詞出現的次數)
  16. String[] sList = s.split(" |,|\\.");//使用split方法將字符串s按空格、逗號和句點分割開,並存在字符數組sList中
  17. for(int i=0; i<sList.length; i++){//遍歷sList數組
  18. if(!has.containsKey(sList[i])){//如果沒有這個單詞,就將單詞存入key里,value值為1;containsKey方法 判斷集合中是否包含指定的key
  19. has.put(sList[i], 1);
  20. }else{//如果已經存在,就將value值加1;用get方法獲取key對應的value值
  21. has.put(sList[i], has.get(sList[i])+1);
  22. }
  23. }
  24. //使用增強for循環遍歷,通過Entry集合訪問,可以訪問key及其對應的Value值
  25. for(Entry<String, Integer> entry:has.entrySet()){
  26. System.out.println(entry.getKey()+":"+entry.getValue());
  27. }
  28. return sb.toString();
  29. }
  30. }
  31. main方法(創建另一個類):
  32. 方式一:已經指定好了句子
  33. package wordCounts;
  34. import java.util.Scanner;
  35. public class WordCounts{
  36. public static void main(String[] args) {
  37. String sentence = "The most distant way in the world,"
  38. + "is not the way from birth to the end. "
  39. + "It is when I stand in front of you,"
  40. + "but you don't understand I love you.";
  41. System.out.println(StatList(sentence));
  42. }
  43. }
  44. 方式二:從鍵盤輸入
  45. package wordCounts;
  46. import java.util.Scanner;
  47. public class WordCounts{
  48. public static void main(String[] args) {
  49. @SuppressWarnings("resource")
  50. Scanner scanner = new Scanner(System.in);
  51. String ab = scanner.nextLine();
  52. StrList sl = new StrList();
  53. System.out.println(sl.StatList(ab));
  54. }
  55. }
  56. ————————————————


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM