Android Utililty Methods String Shorten

List of utility methods to do String Shorten

Description

The list of methods to do String Shorten are organized into topic(s).

Method

StringaddEllipsis(String src, String ellipsis, int maxLength)
add Ellipsis
if (maxLength < 0) {
    throw new IllegalArgumentException(
            "maxLength could not less than zero");
int srcLength = src.length();
if (srcLength <= maxLength) {
    return src;
int ellipsisLength = ellipsis.length();
int dis = srcLength + ellipsisLength - maxLength;
if (dis < srcLength) {
    return src.substring(0, srcLength - dis) + ellipsis;
return ellipsis.substring(dis - srcLength);
StringtoLength(String str, int length)
to Length
if (str == null) {
    return null;
if (length <= 0) {
    return "";
try {
    if (str.getBytes("GBK").length <= length) {
...
Stringtruncate(String text, int length)
Truncates the string to a particular length while appending ...
if (text == null || text.length() <= length) {
    return text;
return text.substring(0, length - 3) + "...";
StringtruncateAt(String string, int length)
truncate At
return string.length() > length ? string.substring(0, length)
        : string;
Stringcurtail(String str, int size, String tail)
curtail
if (str == null) {
    return null;
int strLen = str.length();
int tailLen = (tail != null) ? tail.length() : 0;
int maxLen = size - tailLen;
int curLen = 0;
int index = 0;
...
StringtruncateString(String resource, String startTag, String endTag)
truncate String
int start = resource.indexOf(startTag);
int end = resource.indexOf(endTag, start + startTag.length());
if (start != -1 && end != -1) {
    resource = resource.substring(start + startTag.length(), end);
    return resource;
return null;
StringtruncateAtMaxLength(String source, int maxLength, boolean addEllipsis)
If this given string is of length maxLength or less, it will be returned as-is.
if (source.length() <= maxLength) {
    return source;
if (addEllipsis && maxLength > 3) {
    return unicodePreservingSubstring(source, 0, maxLength - 3)
            + "...";
return unicodePreservingSubstring(source, 0, maxLength);
...
StringshortenString(String str, int length)
shorten String
if (str.length() > length) {
    String newStr = str.substring(0, length);
    return newStr.concat("...");
return str;
StringellipsizeString(String string, int limit)
ellipsize String
String retValue = "";
if (string != null) {
    if (string.length() > limit) {
        retValue = string.substring(0, limit) + "...";
    } else {
        retValue = string;
return retValue;
Stringellipsize(final String text, final int length)
Ellipsizes a text
String result;
if (TextUtils.isEmpty(text)) {
    result = "";
} else {
    result = text;
    if (result.length() > length) {
        result = result.substring(0, length - 6) + " [...]";
return result;