Java-統計字符串中英文單詞總數

根據輸入的字符串統計其中的英文單詞數量

public int countWords(String str) {  

    String abb = "She   had been shopping,"

                + " this, "

                + "你好呀. "

                + "urry   to,";


        Pattern expression = Pattern.compile("[a-zA-Z]+");//定義正則表達式匹配單詞

        String string1 = abb.toString().toLowerCase();//轉換成小寫

        Matcher matcher = expression.matcher(string1);

        //定義string1的匹配器

        HashMap myTreeMap = new HashMap();//創建樹映射 存放鍵/值對

        int articleWords  = 0;//文章中單詞總數

      while (matcher.find()) {//是否匹配單詞

                      articleWords ++;//單詞數加1

        }

    return articleWords;
}

 

輸出結果:

統計分析如下:
文章中單詞總數7個

參考鏈接:

https://www.cnblogs.com/pochonlee/archive/2008/01/07/949007.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章