java 字符串自动补足_自动省略Java中的字符串

小编典典

根据您的用例,将省略号放在字母之间可能会很有用(即,在末尾添加字母以提供一些上下文):

/**

* Puts ellipses in input strings that are longer than than maxCharacters. Shorter strings or

* null is returned unchanged.

* @param input the input string that may be subjected to shortening

* @param maxCharacters the maximum characters that are acceptable for the unshortended string. Must be at least 3, otherwise a string with ellipses is too long already.

* @param charactersAfterEllipsis the number of characters that should appear after the ellipsis (0 or larger)

* @return the truncated string with trailing ellipses

*/

public static String ellipsize(String input, int maxCharacters, int charactersAfterEllipsis) {

if(maxCharacters < 3) {

throw new IllegalArgumentException("maxCharacters must be at least 3 because the ellipsis already take up 3 characters");

}

if(maxCharacters - 3 > charactersAfterEllipsis) {

throw new IllegalArgumentException("charactersAfterEllipsis must be less than maxCharacters");

}

if (input == null || input.length() < maxCharacters) {

return input;

}

return input.substring(0, maxCharacters - 3 - charactersAfterEllipsis) + "..." + input.substring(input.length() - charactersAfterEllipsis);

}

省略号算法可能还需要其他更复杂的功能:如果需要将文本放入图形元素中并且使用的是比例字体,则必须测量String的长度。

对于Swing /

AWT来说应该是java.awt.Font.getStringBounds。在这种情况下,简单的算法可以一次将字符串切成一个字母并加上省略号,直到字符串符合给定的限制为止。如果经常使用,http://www.codeproject.com/KB/cs/AutoEllipsis.aspx?

msg = 3278640 (C#,但应该足够容易转换为Java)中详细说明的二等分方法可以节省一些处理器周期。

2020-11-01

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值