在Java中自动椭圆化字符串 [英] Automatically ellipsize a string in Java

查看:93
本文介绍了在Java中自动椭圆化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中有一种自动椭圆化字符串的方法吗?只是在Java中,而不是其他库。

Is there a method in Java to automatically ellipsize a string? Just in Java, not other libraries.

谢谢。

推荐答案

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

Depending on your use case, it might be useful to put the ellipsis between letters (i.e. add letters at the end to provide some context):

/**
 * 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);
}

您还可以从省略号算法中获得更复杂的功能:如果您需要将文本放入图形元素并使用比例字体,然后必须测量字符串的长度。

There are also more sophisticated features you might want from you ellipsis algorithm: If you need to place the text into a graphical element and you are using a proportional font, then you must measure the length of the String.

对于Swing / AWT将是 java.awt.Font.getStringBounds 。在这种情况下,一个简单的algrithm会一次一个字母地剪切字符串并添加省略号,直到字符串符合给定的限制。如果经常使用,则在 http://www.codeproject中详细阐述了二分法。 .com / KB / cs / AutoEllipsis.aspx?msg = 3278640 (C#,但应该很容易转换为Java)可以节省一些处理器周期。

For Swing/AWT that would be java.awt.Font.getStringBounds. In such a case, a simple algrithm would cut the string one letter at a time and add the ellipsis, until the string fits into the limit given. If used often, the bisection method elaborated in http://www.codeproject.com/KB/cs/AutoEllipsis.aspx?msg=3278640 (C#, but should be easy enough to translate to Java) may save some processor cycles.

这篇关于在Java中自动椭圆化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆