Share this page 

Ellipse a StringTag(s): String/Number


You "ellipse" a String when you want to display a long String using a shorter representation because of the available space.
public class StringUtils {
  public static final String ELLIPSE = "...";
  public static String toEllipsis(String input, int maxCharacters, int charactersAfterEllipse) {
    if (input == null || input.length() < maxCharacters) {
      return input;
    }
    return input.substring(0, maxCharacters - charactersAfterEllipse)
       + ELLIPSE
       + input.substring(input.length() - charactersAfterEllipse);
  }

  private StringUtils() { }

  public static void main (String args[])
      throws Exception {
    String s = "Real's HowTo @ www.rgagnon.com";
    System.out.println(s);
    // max length is 15 with the last six characters.
    System.out.println(StringUtils.toEllipsis(s, 15, 6));
    // max length is 15 with no character at the end.
    System.out.println(StringUtils.toEllipsis(s, 15, 0));

    /*
     * output :
     *   Real's HowTo @ www.rgagnon.com
     *   Real's Ho...on.com
     *   Real's HowTo @ ...
     */
  }
}

Unicode has a special character to show an ellipsis (to use one character instead of 3) :
public static final String ELLIPSE = "\u2026";
The HTML entity to represent an ellipsis is &hellip; : …

See also this HowTo : Shorten a long path.