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)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 商洛市| 馆陶县| 天镇县| 长兴县| 麦盖提县| 滨海县| 英山县| 开远市| 邛崃市| 石屏县| 德保县| 日照市| 同德县| 松滋市| 承德县| 炉霍县| 吕梁市| 兴国县| 玛纳斯县| 武义县| 堆龙德庆县| 林周县| 阜城县| 温州市| 新津县| 达州市| 独山县| 呈贡县| 修文县| 德昌县| 德钦县| 元谋县| 丘北县| 苍梧县| 资溪县| 池州市| 红桥区| 台东县| 陇西县| 炉霍县| 依兰县|