在java中,字符串“abcd”与字符串“ab你好”的长度是一样,都是四个字符。
但对应的字节数不同,一个汉字占两个字节。
定义一个方法,按照指定的字节数来取子串。
如:对于“ab你好”,如果取三个字节,那么子串就是ab与“你”字的半个,那么半个就要舍弃。如果取四个字节就是“ab你”,取五个字节还是“ab你”。
public class StringCutDemo {
@Test//GBKpublic void t1() throws IOException{
String str="人生最美不过初见";
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) throws IOException{
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");
}
}
private static String cutStringByByteUtf8(String str,int len) throws IOException{
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");
}
private static String cutStringByByte(String str,int len) throws IOException{
if(System.getProperty("file.encoding").equalsIgnoreCase("gbk")){
return cutStringByByteGbk(str, len);
}else{
return cutStringByByteUtf8(str, len);
}
}
public static void main(String[] args) throws IOException {
String str="人生最美不过初见";
//System.out.println(str.getBytes().length);
for(int i=1;i<=str.getBytes().length;i++){
System.out.println(i+":"+cutStringByByte(str, i));
}
}
}