用省略号截断字符串的理想方法
我相信我们所有人都在Facebook状态(或其他地方)看过省略号,然后点击“显示更多”并且只有另外两个字符左右。我猜这是因为懒惰的编程,因为肯定有一种理想的方法。
我将细长的字符[iIl1]称为“半字符”,但是当它们几乎不隐藏任何字符时,这并不会使省略号看起来很傻。
有理想的方法吗?这是我的:
/**
* 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;
}
语言并不重要,但标记为Java,因为这是我最感兴趣的内容。
萧十郎
相关分类