Java String Truncate trunc(String string, int length)

Here you can find the source of trunc(String string, int length)

Description

Truncates the String by removing characters from the right side of the String so it is length characters long.

License

Apache License

Parameter

Parameter Description
string the string to truncate
length The final length of the new string after trucating

Return

the truncated string

Declaration

public static String trunc(String string, int length) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from  w ww.  j  a  v  a 2  s  .c  o m*/
     * Truncates the String by removing characters from the right side of the
     * String so it is length characters long. If the String is already length
     * characters long or less then the string is returned. If a negative length
     * is specified the characters are removed from the left side of the string.
     * 
     * @param string
     *            the string to truncate
     * @param length
     *            The final length of the new string after trucating
     * @return the truncated string
     */
    public static String trunc(String string, int length) {

        int absLength = Math.abs(length);

        if ((string == null) || (string.length() <= absLength)) {
            return string;
        }

        if (length < 0) {
            int sLength = string.length();
            return string.substring(sLength - absLength, sLength);
        }

        return string.substring(0, length);
    }
}

Related

  1. trunc(String in, int len)
  2. trunc(String s, int length)
  3. trunc(String s1, int length)
  4. trunc(String str, int length)
  5. trunc(String txt, int size)
  6. trunc(String value, int len)
  7. truncate(final String description)
  8. truncate(final String in, final int maxLen)