风扬  

截取指定长度的字符串,如果超出就用more的内容来替换
 截取的字节数,截取的时候,有可能会少截取一位(当最后一位是1个双字节的话,会少截取一个)

public class Test {
    public static void main(String[] args) {
        String s="a测试bcd试1";
        System.err.println(subAndReplaceString(s, 50, "..."));
    }
    
    public static String subAndReplaceString(String str, int toCount, String more) {
        int reInt = 0;
        String reStr = "";
        if (str == null)
            return "";
        char[] tempChar = str.toCharArray();
        for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
            String s1 = String.valueOf(tempChar[kk]);
            byte[] b = s1.getBytes();
            reInt += b.length;
            if (reInt > toCount)
                break;
            reStr += tempChar[kk];
        }
        if (toCount == reInt || (toCount == reInt - 1))
            reStr += more;
        return reStr;
    }
}

posted on 2013-11-07 12:11  风扬扬  阅读(251)  评论(0编辑  收藏  举报