Java---練習(面試題) :字串截取(2-最終版)__java

來源:互聯網
上載者:User

在java中,字串“abcd”與字串“ab你好”的長度是一樣,都是四個字元。
但對應的位元組數不同,一個漢字佔兩個位元組。
定義一個方法,按照指定的位元組數來取子串。
如:對於“ab你好”,如果取三個位元組,那麼子串就是ab與“你”字的半個,那麼半個就要捨棄。如果取四個位元組就是“ab你”,取五個位元組還是“ab你”。

上面給出的是在gbk編碼下的截取字串。
下面我寫了個代碼,可以在utf-8和gbk編碼下都能截取字串。

注意:utf-8下的絕大多數漢字都是3個位元組,所以,為了簡化,全部當成了3個位元組處理。

注意:
在上一個中,我把題意理解錯了,其實題目要求的只是輸出第一個n位元組的字串就可以了。
在上一個中我是把一個字串按照n拆分了。。。。

package io.app;import java.io.IOException;import org.junit.Test;/** *  * @author 陳浩翔 * * @version 1.0  2016-4-28 */public class StringCut {    public static void main(String[] args) {        String str = "ab你好a琲琲";        byte bf[] = str.getBytes();//這裡是採用預設編碼,可能是GBK,也可能是UTF-8        for(int i=0;i<=bf.length;i++){            String res;            try {                res = cutString(str,i);                System.out.println(i+" : "+res);            } catch (IOException e) {                e.printStackTrace();            }        }    }    /**     * 根據傳入的字串,來判斷是什麼編碼的,分別導向不同的方法     * @param str     * @param len     * @return     * @throws IOException      */    private static String cutString(String str, int len) throws IOException {        //System.getProperty("file.encoding")---獲得系統的編碼        if(System.getProperty("file.encoding").equalsIgnoreCase("gbk")){            return cutStringGbk(str, len);        }        if(System.getProperty("file.encoding").equalsIgnoreCase("utf-8")){            return cutStringUtf8(str, len);        }        throw new RuntimeException("不支援當前系統的編碼");    }    private static String cutStringUtf8(String str, int len) throws IOException {        byte buf[] = str.getBytes("utf-8");        int count=0;        for(int i=len-1;i>=0;i--){            if(buf[i]<0){                count++;            }else{                break;            }        }        int x = count%3;        return new String(buf,0,len-x,"utf-8");    }    private static String cutStringGbk(String str, int len) throws IOException {        byte buf[] = str.getBytes("gbk");        int count=0;        for(int i=len-1;i>=0;i--){            if(buf[i]<0){                count++;            }else{                break;            }        }        if(count%2==0){            return new String(buf,0,len,"gbk");        }else{            return new String(buf,0,len-1,"gbk");        }    }    @Test    /**     * 可以不需要main方法進行運行單個方法。。。。     * @throws IOException     */    public void analyze() throws IOException {        //String str ="ab你好";        String str ="ab你好a琲琲琲";        //byte buf[] = str.getBytes("gbk");        byte buf[] = str.getBytes("utf-8");        for(byte b:buf){            System.out.print(b+" ");        }        System.out.println();    }}

GBK下的運行結果:
(漢字為2個位元組)

0 : 1 : a2 : ab3 : ab4 : ab你5 : ab你6 : ab你好7 : ab你好a8 : ab你好a9 : ab你好a琲10 : ab你好a琲11 : ab你好a琲琲

UTF-8下的運行結果:
(漢字理解為3個位元組)

0 : 1 : a2 : ab3 : ab4 : ab5 : ab你6 : ab你7 : ab你8 : ab你好9 : ab你好a10 : ab你好a11 : ab你好a12 : ab你好a琲13 : ab你好a琲14 : ab你好a琲15 : ab你好a琲琲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.