Truncate a text after maxLength chars. - Java java.lang

Java examples for java.lang:String Truncate

Description

Truncate a text after maxLength chars.

Demo Code

public class Main {
  public static void main(String[] argv) {
    String input = "java2s.com";
    int maxLength = 4;
    System.out.println(ellipsis(input, maxLength));
  }//from  w  w w .  j  a  v a  2s  .  co  m

  /**
   * Truncate a text after maxLength chars. If the text was longer than maxLength,
   * three dots are added (…).
   *
   * @param input
   *          the input string
   * @param maxLength
   *          the maximum String length to allow before truncating
   * @return truncated string
   */
  public static String ellipsis(final String input, final int maxLength) {
    StringBuilder output = new StringBuilder(truncate(input, maxLength));
    if (input.length() > maxLength) {
      output.append("…");
    }
    return output.toString();
  }

  /**
   * A safer, smarter truncate that doesn't complain if length is greater than the
   * string length.
   *
   * @param str
   *          the input string
   * @param length
   *          how many chars to allow as a max
   * @return the truncated string (which can be the same of the original if it was
   *         already within length)
   * @throws IllegalArgumentException
   *           if length was negative
   */
  public static String truncate(final String str, final int length) throws IllegalArgumentException {
    String out;
    if (length < 0) {
      throw new IllegalArgumentException("negative length is not allowed. (length=" + length + ")");
    }
    if (str.length() <= length) {
      out = str;
    } else {
      out = str.substring(0, length);
    }
    return out;
  }
}

Related Tutorials