Friday, November 6, 2009

Nicely truncating text with Java (by adding “…”)

Sometimes we have to show long text in place that is too small. Simply truncating text is not so nice, and it does not visually implies that there is more text after the truncation. We can use Java to easily truncate text nicely by adding “…” instead of the truncated part. We will construct 2 functions:

  • Truncate a string to a fixed maximum length and leave a request amount of characters from the end of the string. For example, if we have the text: “This is some long text test, This is some long text test, This is some long text test”, and we would like to truncate the text to be maximum size of 30 characters and leave 12 characters from the end of the string, the result would look like: “This is some lo...ng text test”. Note, that the “…” along with the string itself constructs no more than 30 characters.
  • The second function is a special case of the first function: we would like to truncate a string to a fixed maximum length, by leaving “…” at the end of the string. For example if we use the previous string, the result of truncating it will look like: “This is some long text test...”. Note, that again, the maximum length of string along with the “…” is no more than 30 characters.

Writing these 2 functions in Java is a very simple task that mainly takes advantage substring method:

package com.bashan.blog.string;
public class StringUtils {
  public static String truncateText(String str, int maxLen, int lenFromEnd) {
    int len;
    if (str != null && (len = str.length()) > maxLen) {
      return str.substring(0, maxLen - lenFromEnd - 3) + "..." +
          str.substring(len - lenFromEnd, len);
    }
    return str;
  }
  public static String truncateText(String str, int maxLen) {
    return truncateText(str, maxLen, 0);
  }
  public static void main(String[] args) {
    String str = "This is some long text test, This is some long text test, This is some long text test";
    System.out.println(truncateText(str, 30, 12));
    System.out.println(truncateText(str, 30));
  }
}

At the end we can see a small test program. The output for it is:

This is some lo...ng text test
This is some long text test...

No comments:

Post a Comment