汉字英文混合字符串 截取指定字符串长度

import org.junit.Test;

public class Split {
    public static void main(String[] args) throws Exception {
        split("我ABC汗DEF", 6);
    }

    public static void split(String source, int num) throws Exception {
        int k = 0;
        String temp = "";// 如果前面是汉字 ,则后面的算一个字节,如果不是汉字,后面的不算字节
        byte[] a = ("你" + "").getBytes();
        System.out.println("a:" + a.length);
        for (int i = 0; i < source.length(); i++) {
            byte[] b = (source.charAt(i) + "").getBytes();
            System.out.println(b.length);
            k = k + b.length;
            if (k > num) {
                break;
            }
            temp = temp + source.charAt(i);
        }
        System.out.println(temp);
    }

    @Test
    public void s() {
        String source = "我ABC汗DEF";
        int num = 6;
        int k = 0;
        String temp = "";
        for (int i = 0; i < source.length(); i++) {
            byte[] b = (source.charAt(i) + "").getBytes();
            k = k + b.length;
            if (k > num) {
                break;
            }
            temp = temp + source.charAt(i);
        }
        System.out.println(temp);
    }
}

你可能感兴趣的:(中英文字符截取)