- public static String substring(String str, int length) {
- byte[] bytes = null;
- String s = null; // 需要输出的字符串
- try {
- // 将字符串转换为字节
- bytes = str.getBytes("GBK");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- // 判断字节长度,如果需要截取的长度大于字节长度,则不执行
- if (bytes.length < length) {
- System.out.println("截取的字节数不能大于字符串字节数!");
- } else {
- s = new String(bytes, 0, length);
- int len = s.length();
- //判断是否出现了截半,如果出现截半,将字节指针左移一位
- if (str.charAt(len-1)!= s.charAt(len-1)) {
- s = new String(bytes,0,length-1);
- }
- }
- return s;
- }
- public static void main(String[] args) throws Exception {
- String s = "HM程序员";
- System.out.println(substring(s,5));
- }
复制代码
|