服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

截取指定长度的字符串

    /**
     * 截取指定长度的字符串,中文算2个长度,若过长,返回xxx...,否则返回原串
     * @param s original string.
     * @param max max length.
     * @return left part of string.
     */
    public static string left(string s, int max) {
        char[] cs = s.tochararray();
        int count = 0;
        int last = cs.length;
        for(int i=0; i<cs.length; i++) {
            if(cs[i]>255)
                count+=2;
            else
                count++;
            if(count>max) {
                last = i+1;
                break;
            }
        }
        if(count<=max) // string is short or just the size!
            return s;
        // string is too long:
        max -= 3;
        for(int i=last-1; i>=0; i--) {
            if(cs[i]>255)
                count-=2;
            else
                count--;
            if(count<=max) {
                return s.substring(0, i) + "...";
            }
        }
        return "...";
    }

扫描关注微信公众号