小编典典

自动省略Java中的字符串

java

Java中有没有一种方法可以自动省略一个字符串?仅使用Java,而不是其他库。

谢谢。


阅读 225

收藏
2020-11-01

共1个答案

小编典典

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

/**
 * 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