编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节
截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB
”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
按照GBK编码规范,如果一个字节无符号值大于127,则不管后面一个字节大小是多少,这两个字节共同表示一
个汉字。
问题的关键在于考虑截取长度的最后一个字节和倒数第二个字节,如果最后一个字节是属于一个汉字的第一个字
节,忽略即可;如果倒数1,2个字节构成一个汉字,就不需要截取。
注意:此题目未明确声明编码规范,但中文平台下默认的编码规范为"GBK",故按此规范操作,源码如下。
package com.string;
import java.io.UnsupportedEncodingException;
public class SplitString {
public String str;
public int bytes;
public byte[] strBytes;
public byte[] result;
public byte[] another;
//字节大于127,值是负数
public byte border = 0;
public SplitString(String str, int bytes){
this.str = str;
this.bytes = bytes;
System.out.println("The String is: "+str+" ; Bytes is : "+bytes);
}
public void split(){
try{
strBytes = str.getBytes("GBK");
result = new byte[bytes];
another = new byte[bytes-1];
for(int i=0;i<result.length;i++){
result[i] = strBytes[i];
}
//判断是否汉字第一个字符(无符号值>127;带符号则<0,为负数!)
if(result[result.length-1]<border){
if(result[result.length-2]<border){
System.out.println(new String(result));
return;
}
for(int i=0;i<another.length;i++){
another[i]=result[i];
}
System.out.println(new String(another));
}else{
System.out.println(new String(result));
}
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
SplitString amao;
//amao = new SplitString("我ABC",4);
amao = new SplitString("我ABC汉DEF",7);
amao.split();
}
}