试题----编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个

一、需要分析

1、输入为一个字符串和字节数,输出为按字节截取的字符串--------》按照字节[byte]截取操作字符串,先将String转换成byte类型

2、汉字不可以截半----------》汉字截半的话对应字节的ASC码为小于0的数值

二、技术难点

1、知道汉字截半的话对应字节的ASC码为小于0的数值

2、对字符串操作应该都要面对的一个问题,字符串是否有效null, 字符串的长度0,1这种边界处理

public class Test1 {  
  
    public static void main(String[] args) {  
        String srcStr1 = "我ABC";  
        String srcStr2 = "我ABC汉DEF";  
  
        splitString(srcStr1, 4);  
        splitString(srcStr2, 6);  
    }  
  
    public static void splitString(String src, int len) {  
        int byteNum = 0;  
  
        if (null == src) {  
            System.out.println("The source String is null!");  
            return;  
        }  
  
        byteNum = src.length();  
        byte bt[] = src.getBytes(); // 将String转换成byte字节数组  
  
        if (len > byteNum) {  
            len = byteNum;  
        }  
  
        // 判断是否出现了截半,截半的话字节对于的ASC码是小于0的值  
        if (bt[len] < 0) {  
            String subStrx = new String(bt, 0, --len);  
            System.out.println("subStrx==" + subStrx);  
        } else {  
            String subStrx = new String(bt, 0, len);  
            System.out.println("subStrx==" + subStrx);  
        }  
    }  
  
}  

 结果

subStrx==我AB  
subStrx==我ABC 
原文地址:https://www.cnblogs.com/day93110/p/6094205.html