Here you can find the source of ellipsize(String text, int max)
public static String ellipsize(String text, int max)
//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); } }