A safer, smarter truncate that doesn't complain if length is greater than the string length. - Java java.lang

Java examples for java.lang:String Truncate

Description

A safer, smarter truncate that doesn't complain if length is greater than the string length.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        int length = 4;
        System.out.println(truncate(str, length));
    }//  w ww  . j a  v a2 s.co m

    /**
     * A safer, smarter truncate that doesn't complain if length is greater
     * than the string length.
     *
     * @param str
     * the input string
     * @param length
     * how many chars to allow as a max
     * @return the truncated string (which can be the same of the original
     * if it was already within length)
     * @throws IllegalArgumentException
     * if length was negative
     */
    public static String truncate(final String str, final int length)
            throws IllegalArgumentException {
        String out;
        if (length < 0) {
            throw new IllegalArgumentException(
                    "negative length is not allowed. (length=" + length
                            + ")");
        }
        if (str.length() <= length) {
            out = str;
        } else {
            out = str.substring(0, length);
        }
        return out;
    }
}

Related Tutorials