1. 程式人生 > >編寫一個擷取字串的函式,輸入為一個字串和位元組數, 輸出為按位元組擷取的字串。 但是要保證漢字不被截半個。

編寫一個擷取字串的函式,輸入為一個字串和位元組數, 輸出為按位元組擷取的字串。 但是要保證漢字不被截半個。

題目: 編寫一個擷取字串的函式,輸入為一個字串和位元組數, 輸出為按位元組擷取的字串。 但是要保證漢字不被截半個,如“我ABC”4, 應該截為“我AB”,輸入“我ABC漢DEF”,6, 應該輸出為“我ABC”而不是“我ABC+漢的半個”。

package cn.itchg;

/**
 * Created by CHG on 2017-02-23 14:48.
 */
public class GBK {

    public static void main(String[] args) throws Exception {
        String string = "我a很bc你好"
; System.out.println(splitString(string, 1)); } public static String splitString(String str, int length) throws Exception { //無效輸入 if (str == null || str.length() < 1 || length < 1) { return ""; } //用於統計這個字串中有幾個中文字元 int
wordCount = 0; //統一按照gbk編碼來得到他的位元組陣列,因為不同的編碼位元組陣列是不一樣的。 byte[] gbks = str.getBytes("GBK"); //gbks中,漢字是兩個負數表示 for (int i = 0; i < length; i++) { int val = gbks[i]; if (val < 0) { //漢字個數++ wordCount++; } } //完整的漢字
if (wordCount % 2 == 0) { return str.substring(0, (length - (wordCount / 2))); } //半個漢字 所以 -1 return str.substring(0, (length - (wordCount / 2) - 1)); } }