public class SubStringTest {

    @Test
    public void test() {

        String s = "北京市丰台区东铁营街道政馨园社区1区1号楼1层";
        System.out.println(subString(s, 58));
    }

    public static String subString(String source, int length) {

        StringBuffer buffer = new StringBuffer();
        char[] chars = source.toCharArray();
        char c;
        for (int i = 0;; i++) {
            if (length <= 0) {
                break;
            }
            c = source.charAt(i);
            buffer.append(c);
            length -= String.valueOf(c).getBytes().length;
            if (i + 1 < chars.length) {
                if (String.valueOf(chars[i + 1]).getBytes().length > length) {
                    break;
                };
            }
        }
        return buffer.toString();
    }
}

 

 posted on 2020-01-09 23:59  小网民  阅读(1276)  评论(0编辑  收藏  举报