大大毛 的筆記

            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

          主站蜘蛛池模板: 广东省| 西贡区| 塔河县| 丰原市| 土默特左旗| 高邑县| 惠水县| 砀山县| 渭源县| 宿迁市| 罗江县| 周至县| 南汇区| 怀远县| 东明县| 盐边县| 桂平市| 岳普湖县| 伊春市| 宝坻区| 顺义区| 凤翔县| 澜沧| 临汾市| 永德县| 资兴市| 寿阳县| 英超| 息烽县| 招远市| 申扎县| 仙桃市| 玛多县| 潮安县| 叶城县| 曲阳县| 滨海县| 即墨市| 陆河县| 澄江县| 从江县|