oss

public String truncStrBySize(String source)
    {
        if (source == null)
            return null;
        int start, stop, byteLen;
        int alen = source.getBytes().length;

        if (len > 0)
        {
            if (alen <= len)
                return source;
            start = stop = byteLen = 0;
            while (byteLen <= len && stop < source.length())
            {
                if (source.substring(stop, stop + 1).getBytes().length == 1)
                {
                    byteLen += 1;
                }
                else
                {
                    byteLen += 2;
                }
                stop++;
            }
            StringBuffer sb = new StringBuffer(source.substring(start, stop - 1));
            if (alen > len)
                sb.append(delim);
            return sb.toString();
        }
        start = (len < -alen ? 0 : alen + len);
        stop = alen;
        StringBuffer sb = new StringBuffer(source.substring(start / 2, stop / 2));
        if (-alen <= len)
            sb.insert(0, delim);
        return sb.toString();
    }

猜你喜欢

转载自yannis-q.iteye.com/blog/1343698
oss