Java String Ellipse ellipsize(String text, int max)

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

Description

From <a href="http://stackoverflow.com/a/3657496/3802890">StackOverflow</a>

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 {
    /**//from   w  ww .  j  av  a 2 s  .c o m
     * From <a href="http://stackoverflow.com/a/3657496/3802890">StackOverflow</a>
     */
    public static String ellipsize(String text, int max) {
        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 - 3);

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

        // 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) + "...") < max);

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

    private static int textWidth(String str) {
        return str.length() - str.replaceAll("[^iIl1\\.,']", "").length() / 2;
    }
}

Related

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