posts - 73,  comments - 55,  trackbacks - 0
          /*
          ?*?題目:
          ?*?編寫一個截取字符串的函數,輸入為一個字符串和字節數,輸出為按字節截取的字符串。?但是要保證漢字不被截半個,如“我ABC”4,應該截為“我AB”,輸入“我ABC漢DEF”,6,應該輸出為“我ABC”而不是“我ABC+漢的半個”。?
          ?*?
          ?*?解釋:
          ?*?此處的編碼方式應該是操作系統默認的GB編碼,即漢字占2個字節且第一個字節的最高位是1,
          ?*?如果理解為有符號數的話,就是負數;而英文占1個字節,符合ASC2碼。
          ?
          */

          class ?SplitString?
          {
          ?
          private ?String?str;
          ?
          private ? int ?byteNum;

          ?
          public ?SplitString() {}

          ?
          public ?SplitString(String?str, int ?byteNum)
          ?
          {
          ??
          this .str = str;
          ??
          this .byteNum = byteNum;

          ?}

          ?
          ?
          public ? void ?splitIt()
          ?
          {

          ??
          byte ?bt[] = str.getBytes();
          ??System.out.println(
          " Length?of?this?String?===> " + bt.length);
          ??
          if (byteNum >= 1 )
          ??
          {
          ???
          if (bt[byteNum] < 0 )
          ???
          {
          ????String?substrx
          = new ?String(bt, 0 , -- byteNum);
          ????System.out.println(substrx);
          ???}
          else
          ???
          {
          ????String?substrex
          = new ?String(bt, 0 ,byteNum);
          ????System.out.println(substrex);
          ???}

          ??}
          else
          ??
          {?
          ???System.out.println(
          " 輸入錯誤!!!請輸入大于零的整數: " );
          ??}

          ?}

          }


          public ? class ?TestSplitString
          {
          ?
          public ? static ? void ?main(String?args[])
          ?
          {
          ??String?str
          = " 我ABC漢DEF " ;
          ??
          int ?num = 6 ;
          ??SplitString?sptstr?
          = ? new ?SplitString(str,num);
          ??sptstr.splitIt();
          ?}

          }
          posted on 2007-03-06 17:17 保爾任 閱讀(1696) 評論(1)  編輯  收藏 所屬分類: Arithmetic & Data Structure

          FeedBack:
          # re: java用字節數截取字符串[未登錄]
          2011-08-26 14:44 | dj
          f (bt[byteNum] < 0 )
          {
          String substrx = new String(bt, 0 , -- byteNum);
          System.out.println(substrx);
          }
          //這樣寫,存在bug,如果,比如 “中國人”,6, 按你這樣,得到的結果就是“中國?”  回復  更多評論
            

          <2007年3月>
          25262728123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          常用鏈接

          留言簿(4)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 台东市| 观塘区| 东丽区| 金秀| 灌南县| 徐州市| 兴山县| 鹤壁市| 密山市| 定南县| 阳信县| 舞钢市| 读书| 永仁县| 肥西县| 屯门区| 吉安市| 留坝县| 达拉特旗| 临漳县| 晋江市| 潼关县| 玉田县| 武平县| 桂阳县| 盐池县| 诏安县| 昂仁县| 保德县| 松滋市| 潮安县| 成都市| 自治县| 龙胜| 乌鲁木齐县| 慈溪市| 木兰县| 西青区| 吴忠市| 茶陵县| 唐河县|