Android String Shorten toLength(String str, int length)

Here you can find the source of toLength(String str, int length)

Description

to Length

Declaration

public static String toLength(String str, int length) 

Method Source Code

//package com.java2s;

public class Main {

    public static String toLength(String str, int length) {
        if (str == null) {
            return null;
        }//from  w  w w  .j a v a 2  s . c o m
        if (length <= 0) {
            return "";
        }
        try {
            if (str.getBytes("GBK").length <= length) {
                return str;
            }
        } catch (Exception ex) {
        }
        StringBuffer buff = new StringBuffer();

        int index = 0;
        char c;
        length -= 3;
        while (length > 0) {
            c = str.charAt(index);
            if (c < 128) {
                length--;
            } else {
                length--;
                length--;
            }
            buff.append(c);
            index++;
        }
        buff.append("...");
        return buff.toString();
    }
}

Related

  1. addEllipsis(String src, String ellipsis, int maxLength)
  2. truncate(String text, int length)
  3. truncateAt(String string, int length)
  4. curtail(String str, int size, String tail)
  5. truncateString(String resource, String startTag, String endTag)