天天看點

字元串按指定的位元組數的截取

在Java中字元串“abc123”與字元串“ab你好”的長度是一樣的。都是四個字元,但對應的位元組數不同,一個漢字兩個位元組

定義一個方法,按照指定的位元組數來截取子串

如對于“ab你好”如果取三個位元組,那麼子串就是“ab”與你的半個,那麼辣半個就要舍棄,如果取四個位元組就是”ab你“,取五個位元組還是”ab你“

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import org.junit.Test;

public class StringCutDemo {

@Test //觀察一下位元組資料的規律

public void t1() throws IOException{

String str="ab你好琲a我aa";

print(str.getBytes("gbk"));//一個漢字兩個位元組,第一個位元組是負數,第二個不一定

print(str.getBytes("utf-8"));//一個漢字三個位元組,每個位元組是負數

}

private void print(byte bs[]){

for(byte b:bs){

System.out.print(b+" ");

}

System.out.println();

}

private static String cutStringByByteGbk(String str, int len){

try {

byte bs[] = str.getBytes("gbk");

//從後往前,統計位元組編碼為負數的個數,統計到非負數位元組停止

int count=0;

for(int i=len-1; i>=0; i--){

if(bs[i]<0){

count++;

}else{

break;

}

}

if(count%2==0){//位元組碼值為負的位元組個數為偶數,漢字剛好完整

return new String(bs,0,len,"gbk");

}else{//奇數,要舍去最後一個位元組

return new String(bs,0,len-1,"gbk");

}

} catch (UnsupportedEncodingException e) {

throw new RuntimeException("字元編碼異常,不支援gbk", e);

}

}

@Test //測試cutStringByByteGbk()方法

public void t2() throws IOException{

String str="ab你好琲a我aa";

for(int i=0;i<str.getBytes("gbk").length;i++){

System.out.println(i+":"+ cutStringByByteGbk(str, i) );

}

}

private static String cutStringByByteUtf8(String str, int len){

try {

byte bs[] = str.getBytes("utf-8");

//從後往前,統計位元組編碼為負數的個數,統計到非負數位元組停止

int count=0;

for(int i=len-1; i>=0; i--){

if(bs[i]<0){

count++;

}else{

break;

}

}

return new String(bs,0,len-count%3,"utf-8"); 

} catch (UnsupportedEncodingException e) {

throw new RuntimeException("字元編碼異常,不支援utf-8", e);

}

}

@Test //測試cutStringByByteUtf8()方法

public void t3() throws IOException{

String str="ab你好琲a我aa";

for(int i=0;i<str.getBytes("utf-8").length;i++){

System.out.println(i+":"+ cutStringByByteUtf8(str, i) );

}

}

public static String cutStringByByte(String str, int len){

if(System.getProperty("file.encoding").equalsIgnoreCase("gbk")){

return cutStringByByteGbk(str, len);

}

if(System.getProperty("file.encoding").equalsIgnoreCase("utf-8")){

return cutStringByByteUtf8(str, len);

}

return "";

}

public static void main(String[] args) {

String str="ab你好琲a我aa";

for(int i=0;i<str.getBytes().length;i++){

 System.out.println(i+":"+ cutStringByByte(str, i));

}

}

}