大大毛 的筆記

            DDM's Note

          哪怕沒有辦法一定有說法,
          就算沒有鴿子一定有烏鴉,
          固執無罪 夢想有價,
          讓他們驚訝.

          posts - 14, comments - 23, trackbacks - 0, articles - 58
             :: 首頁 ::  :: 聯系 ::  :: 管理

          統計中英文字數的簡單方法

          Posted on 2006-04-17 00:33 大大毛 閱讀(2227) 評論(1)  編輯  收藏 所屬分類: JAVA
          ??? 翻了翻以前積累下的一些資料,看到其中有一個統計中英文字符數的例子,很簡單,感覺也比較有意思,一直以來都沒有這么去想過問題,現在把它記下來。
          import ?java.io. * ;

          public ? class ?Test?
          {
          ????
          /**
          ?????*?統計字串中中文字符數量
          ?????*?
          @param ?str:GB編碼字符串
          ?????
          */

          ????
          public ? static ? int ?statGBCharCount1(String?str)? {
          ????????
          int ?GBCount? = ? - 1
          ;
          ????????String?otherStr?
          = ? null
          ;
          ????????
          ????????
          try
          {
          ????????????otherStr?
          = ? new ?String(str.getBytes(), " ISO8859_1 "
          );
          ????????????GBCount?
          = ?otherStr.length()? -
          ?str.length();
          ????????}
          catch (UnsupportedEncodingException?ex) {
          ????????????
          throw ? new ?RuntimeException( " UnsupportedEncodingException "
          );
          ????????}

          ????????
          ????????
          return ?GBCount;
          ????}

          ????
          /**
          ?????*?統計字串中中文字符數量
          ?????
          */

          ????
          public ? static ? int ?statGBCharCount2(String?str)? {
          ????????
          int ?GBCount? = ? - 1
          ;
          ????????
          ????????GBCount?
          = ?str.replaceAll( " [\u0000-\u0127] " , ""
          ).length();
          ????????System.out.println(
          " asc字符: " ? + ?str.replaceAll( " [\u0000-\u0127] " , ""
          ));
          ????????System.out.println(
          " 非asc字符: " ? + ?str.replaceAll( " [^\u0000-\u0127] " , ""
          ));
          ????????
          ????????
          return
          ?GBCount;
          ????}

          ????
          ????
          public ? static ? void ?main(String[]?args)? {
          ????????String?str?
          = ? " This?is?test?string?這是一個測試字符串 "
          ;
          ????????System.out.println(
          " 中文字符數: " +
          ?Test.statGBCharCount1(str));
          ????????System.out.println(
          " 中文字符數: " +
          ?Test.statGBCharCount2(str));
          ????}


          }


          可以看到,方法1中使用的辦法,可能局限性更大,不過也是一種思路。
          自己想的是第2種方法,用正則表達式直接過濾,也挺快捷。

          評論

          # re: 統計中英文字數的簡單方法  回復  更多評論   

          2006-11-07 08:58 by vteogdskf
          支持哦......

          i am ddm

          主站蜘蛛池模板: 汉阴县| 漠河县| 久治县| 墨竹工卡县| 梁山县| 池州市| 福贡县| 锡林郭勒盟| 甘孜| 逊克县| 罗定市| 且末县| 凌海市| 开平市| 威宁| 祁连县| 藁城市| 女性| 保德县| 柯坪县| 通城县| 沂南县| 闻喜县| 太原市| 巴南区| 莲花县| 稷山县| 大渡口区| 扎鲁特旗| 云浮市| 望都县| 烟台市| 奇台县| 巴彦淖尔市| 永仁县| 永济市| 县级市| 乌兰浩特市| 建宁县| 武城县| 巴东县|