Java String Ellipse ellipsize(String text, int max)

Here you can find the source of ellipsize(String text, int max)

Description

ellipsize

License

Apache License

Declaration

public static String ellipsize(String text, int max) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    private final static String NON_THIN = "[^iIl1\\.,']";

    public static String ellipsize(String text, int max) {
        return cut(text, max, "...", false);
    }//from  ww w. ja va  2  s  . co  m

    private static String cut(String text, int max, String trail, boolean includeSize) {
        if (text == null) {
            return "null";
        }

        String suffix = trail;
        if (includeSize) {
            suffix = suffix + " (length=" + text.length() + ")";
        }
        int suffixLength = suffix.length();

        if (textWidth(text) <= max)
            return text;

        // Start by chopping off at the word before max
        // This is an over-approximation due to thin-characters...
        int end = text.lastIndexOf(' ', max - suffixLength);

        // Just one long word. Chop it off.
        if (end == -1)
            return text.substring(0, max - suffixLength) + suffix;

        // Step forward as long as textWidth allows.
        int newEnd = end;
        do {
            end = newEnd;
            newEnd = text.indexOf(' ', end + 1);

            // No more spaces.
            if (newEnd == -1)
                newEnd = text.length();

        } while (textWidth(text.substring(0, newEnd) + suffix) < max);

        return text.substring(0, end) + suffix;
    }

    public static String cut(String text, int max) {
        return cut(text, max, "", false);
    }

    private static int textWidth(String str) {
        return (int) (str.length() - str.replaceAll(NON_THIN, "").length() / 2);
    }
}

Related

  1. ellipsisText(String text, int maxLength)
  2. ellipsize(String input, int maxLength)
  3. ellipsize(String s, int maxChars)
  4. ellipsize(String string, int length)
  5. ellipsize(String text, int max)
  6. ellipsize(String text, int maxLength)
  7. ellipsizeKeepingExtension(String s, int maxChars)