Java String Truncate truncate(String str, int length)

Here you can find the source of truncate(String str, int length)

Description

Truncates the given string so it is no longer than the given length, which must be at least three.

License

Open Source License

Parameter

Parameter Description
str The string to truncate.
length The maximum length of the desired string, which must be at least three.

Return

The given string, truncated to at most length characters, with "..." at its end if it is truncated.

Declaration

public static String truncate(String str, int length) 

Method Source Code

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

public class Main {
    /**/*from   ww  w. j  ava 2  s. c  om*/
     * Truncates the given string so it is no longer
     * than the given length, which must be at least
     * three.
     * @param str The string to truncate.
     * @param length The maximum length of the desired
     * string, which must be at least three.
     * @return The given string, truncated to at most
     * length characters, with "..." at its end if
     * it is truncated.
     */
    public static String truncate(String str, int length) {
        assert length >= 3 : length;
        length = length - 3;
        if (str.length() <= length)
            return str;
        else
            return str.substring(0, length) + "...";
    }
}

Related

  1. truncate(String str, int chars)
  2. truncate(String str, int len)
  3. truncate(String str, int length)
  4. truncate(String str, int length)
  5. truncate(String str, int length)
  6. truncate(String str, int max)
  7. truncate(String str, int max)
  8. truncate(String str, int maxLen)
  9. truncate(String str, int maxSize)