Java String Truncate truncateStr(String str, int maxNumChars)

Here you can find the source of truncateStr(String str, int maxNumChars)

Description

Truncates a string and adds an ellipse string to the end.

License

Open Source License

Parameter

Parameter Description
str the string to be truncated.
maxNumChars maximum num of characters in the string, including additional characters of the ellipse string.

Declaration

public static String truncateStr(String str, int maxNumChars) 

Method Source Code

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

public class Main {
    /**//w  ww  .j  a  va 2s.c om
     * Truncates a string and adds an ellipse string to the end. Note that if the string passed in is not longer the
     * [len(str) - len(ellipse)], then nothing happens and the string is simply returned as it was passed in.
     * 
     * @param str
     *          the string to be truncated.
     * @param maxNumChars
     *          maximum num of characters in the string, including additional characters of the ellipse string.
     * @returns the truncated string
     */
    public static String truncateStr(String str, int maxNumChars) {
        final String ellipse = "...";

        if (str == null)
            return "";

        if (str.length() >= maxNumChars) {
            StringBuffer newStr = new StringBuffer(maxNumChars);
            newStr.append(str.substring(0, maxNumChars - 1 - ellipse.length()));
            newStr.append(ellipse);
            return newStr.toString();
        } else {
            return str;
        }
    }
}

Related

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