Java String Truncate truncate(String input, int maxLength)

Here you can find the source of truncate(String input, int maxLength)

Description

Truncates the input sting so that it is not longer than maxLength.

License

Open Source License

Exception

Parameter Description
IllegalArgumentException If maxLength < 3 (needed for the '...' characters).

Declaration

public static String truncate(String input, int maxLength) throws IllegalArgumentException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** Truncates the input sting so that it is not longer than maxLength. If it is, it will replace all the excess text with "...". The total length including the '...' will not exceed maxLength.
     * If input is null, returns null.//from   w w  w.j a v  a2s .c  o m
     * @throws IllegalArgumentException If maxLength < 3 (needed for the '...' characters).
     * */
    public static String truncate(String input, int maxLength) throws IllegalArgumentException {
        String ellipsis = "\u2026";
        return truncate(input, maxLength, ellipsis);
    }

    public static String truncate(final String input, final int maxLength, final String ellipsis) {
        if (input == null)
            return null;
        if (input.length() < maxLength)
            return input;
        if (maxLength < ellipsis.length())
            throw new IllegalArgumentException("maxLength must be at least " + ellipsis.length());
        return input.substring(0, maxLength - ellipsis.length()) + ellipsis;
    }
}

Related

  1. truncate(final String target, final int maxSize)
  2. truncate(final String value, final int width)
  3. truncate(Object truncateMe, int maxLength, String suffix)
  4. truncate(String eval, String suffix, int targetLength)
  5. truncate(String input, int maxLength)
  6. truncate(String input, int size)
  7. truncate(String message)
  8. truncate(String message, int length, boolean includeCount)
  9. truncate(String message, String substring)