Here you can find the source of truncateString(final String str, final int iMaxLength)
Parameter | Description |
---|---|
str | String to truncate, if necessary. Can be null. |
iMaxLength | Maximal length incl. additional information to be added when truncating is necessary. |
public static String truncateString(final String str, final int iMaxLength)
//package com.java2s; public class Main { /**/*from w ww . j a v a 2 s. c om*/ * Truncates a long string, which cannot be shown in full to the user. * At the end of the truncated string it will tell the total length * of the string, if maximum size allows for it. * * @param str String to truncate, if necessary. Can be null. * @param iMaxLength Maximal length incl. additional information to be added * when truncating is necessary. * * @return A string that is not longer than the maximal length that was * specified. Returns null, if null was passed in as string. */ public static String truncateString(final String str, final int iMaxLength) { String strRet = null; if (str != null) { if (str.length() <= iMaxLength) { strRet = str; } else if (iMaxLength > 50) { final String strAdd = "... (total length of " + str.length() + " characters)"; strRet = str.substring(0, iMaxLength - strAdd.length()) + strAdd; } else if (iMaxLength > 3) { strRet = str.substring(0, iMaxLength - 3) + "..."; } else if (iMaxLength >= 0) { strRet = "...".substring(0, iMaxLength); } else { strRet = ""; } } return strRet; } }