Java String Truncate truncateString(final String str, final int iMaxLength)

Here you can find the source of truncateString(final String str, final int iMaxLength)

Description

Truncates a long string, which cannot be shown in full to the user.

License

Open Source License

Parameter

Parameter Description
str String to truncate, if necessary. Can be null.
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.

Declaration

public static String truncateString(final String str, final int iMaxLength) 

Method Source Code

//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;
    }
}

Related

  1. truncatePrefixFromPath(String fileName)
  2. truncatePunctuation(String authority)
  3. truncateSentence(String input, int length)
  4. truncateShortMessage(final String message)
  5. truncateStr(String str, int maxNumChars)
  6. truncateString(int length, String srcString)
  7. truncateString(String description, int length)
  8. truncateString(String errCode, int length, boolean isRight)
  9. truncateString(String inStr, int maxValue)