Ideal method to truncate a string with ellipsis

Viewed 48243

I'm sure all of us have seen ellipsis' on Facebook statuses (or elsewhere), and clicked "Show more" and there are only another 2 characters or so. I'd guess this is because of lazy programming, because surely there is an ideal method.

Mine counts slim characters [iIl1] as "half characters", but this doesn't get around ellipsis' looking silly when they hide barely any characters.

Is there an ideal method? Here is mine:

/**
 * Return a string with a maximum length of <code>length</code> characters.
 * If there are more than <code>length</code> characters, then string ends with an ellipsis ("...").
 *
 * @param text
 * @param length
 * @return
 */
public static String ellipsis(final String text, int length)
{
    // The letters [iIl1] are slim enough to only count as half a character.
    length += Math.ceil(text.replaceAll("[^iIl]", "").length() / 2.0d);

    if (text.length() > length)
    {
        return text.substring(0, length - 3) + "...";
    }

    return text;
}

Language doesn't really matter, but tagged as Java because that's what I'm mostly interested in seeing.

13 Answers

Most of this solutions don't take font metrics into account, here is a very simple but working solution for java swing that i have used for years now.

private String ellipsisText(String text, FontMetrics metrics, Graphics2D g2, int targetWidth) {
   String shortText = text;
   int activeIndex = text.length() - 1;

   Rectangle2D textBounds = metrics.getStringBounds(shortText, g2);
   while (textBounds.getWidth() > targetWidth) {
      shortText = text.substring(0, activeIndex--);
      textBounds = metrics.getStringBounds(shortText + "...", g2);
   }
   return activeIndex != text.length() - 1 ? shortText + "..." : text;
}

You can also simply implement like this:

mb_strimwidth($string, 0, 120, '...')

Thanks.

Related