Here you can find the source of truncate(Object truncateMe, int maxLength, String suffix)
Parameter | Description |
---|---|
truncateMe | The value to be truncated. |
maxLength | An int with the maximum length. |
suffix | A String. |
public static String truncate(Object truncateMe, int maxLength, String suffix)
//package com.java2s; //License from project: BSD License public class Main { /**/*from w ww.ja va 2 s . c o m*/ * Limits the string value of 'truncateMe' to 'maxLength' characters. * If the string gets curtailed, the configured suffix * (default is "...") is used as the ending of the truncated string. * * @param maxLength An int with the maximum length. * @param truncateMe The value to be truncated. * @return A String. */ public static String truncate(Object truncateMe, int maxLength) { return truncate(truncateMe, maxLength, "..."); } /** * Limits the string value of 'truncateMe' to the specified max length in * characters. If the string gets curtailed, the specified suffix is used as * the ending of the truncated string. * * @param truncateMe The value to be truncated. * @param maxLength An int with the maximum length. * @param suffix A String. * @return A String. */ public static String truncate(Object truncateMe, int maxLength, String suffix) { return truncate(truncateMe, maxLength, suffix, true); } /** * Limits the string value of 'truncateMe' to the latest complete word * within the specified maxLength. If the string gets curtailed, the * specified suffix is used as the ending of the truncated string. * * @param truncateMe The value to be truncated. * @param maxLength An int with the maximum length. * @param suffix A String. * @param defaultTruncateAtWord Truncate at a word boundary if true. * @return A String. */ public static String truncate(Object truncateMe, int maxLength, String suffix, boolean defaultTruncateAtWord) { if (truncateMe == null || maxLength <= 0) { return null; } String string = String.valueOf(truncateMe); if (string.length() <= maxLength) { return string; } if (suffix == null || maxLength - suffix.length() <= 0) { // either no need or no room for suffix return string.substring(0, maxLength); } if (defaultTruncateAtWord) { // find the latest space within maxLength int lastSpace = string.substring(0, maxLength - suffix.length() + 1).lastIndexOf(" "); if (lastSpace > suffix.length()) { return string.substring(0, lastSpace) + suffix; } } // truncate to exact character and append suffix return string.substring(0, maxLength - suffix.length()) + suffix; } }