Java: 按字节的开始位置来截取指定字节数长度的字符串

/**---------------------文件名: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("越界");
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值