用省略号截断字符串的理想方法我相信我们所有人都在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,因为这是我最感兴趣的内容。
3 回答

萧十郎
TA贡献1815条经验 获得超13个赞
我很震惊没有人提到Commons Lang StringUtils #breviate()。
更新:是的,它没有考虑到苗条的角色,但我不同意这一点,考虑到每个人都有不同的屏幕和字体设置,这个页面上的大部分人可能正在寻找像这样的维护库以上。
添加回答
举报
0/150
提交
取消