/**---------------------文件名:InterceptString.java---------------------*/
/* 按字节的开始位置来截取指定字节数长度的字符串 */
public class InterceptString{
private String str;
private byte[] byt;
/**
* 构造器
* @param str 要截取的原字符串
*/
public InterceptString(String str) {
this.str = str;
}
/**
* 按字节位置截取指定字节数长度的字符串
* @param offset 设置要截取的开始位置
* @param len 要截取得字节长度
* @param charset 字符集解码
* @return 返回处理后的字符串
*/
public String interceptStr(int offset , int len , String charset) throws Exception{
System.out.println(offset + " " + len) ;
byt = str.getBytes(charset) ;
int setCount = 0 ;
int lenCount = 0 ;
int i ;
for(i = offset - 1 ; i >= 0 ; i--){
if(byt[i] < 0){
setCount ++ ;
}
}
if(setCount % 2 == 0){
i = offset ;
}else{
i = offset + 1;
}
for( ; i < (offset + len) ; i++){
if(byt[i] < 0){
lenCount ++ ;
}
}
if(setCount % 2 == 0 && lenCount % 2 == 0){
return new String(byt , offset , len , charset);
}
else if(setCount % 2 != 0 && lenCount % 2 == 0){
return new String(byt , offset - 1 , len + 1 , charset);
}
else if(setCount % 2 == 0 && lenCount % 2 != 0){
return new String(byt , offset , len + 1 , charset);
}
else{
return new String(byt , offset - 1 , len + 2 , charset);
}
}
/**
* 主方法测试
*/
public static void main(String[] args) throws Exception{
String testStr = new String("中国good刘翔good!");
InterceptString is = new InterceptString(testStr);
for( int i = 0 ; i < 10 ; i++ ){
int begin = (int)Math.round(Math.random() * testStr.length());
int leng = (int)Math.round(Math.random() * testStr.length());
if((begin + leng) < testStr.length() && leng != 0){
String s = is.interceptStr(begin , leng , "GBK");
System.out.println(s);
}
else{
System.out.println("越界");
}
}
}
}