If a string exceeds a particular length, truncate it and append a suffix that will hopefully allow the string to retain its uniqueness. - Java java.lang

Java examples for java.lang:String Strip

Description

If a string exceeds a particular length, truncate it and append a suffix that will hopefully allow the string to retain its uniqueness.

Demo Code

/*//from  ww  w .  j  av  a 2s. co m
StringUtils.java : A stand alone utility class.
Copyright (C) 2000 Justin P. McCarthy

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.

To further contact the author please email jpmccar@gjt.org


Modifications, copyright 2001-2014 Tuma Solutions, LLC; distributed under the
LGPL, as described above.

 */
//package com.java2s;

public class Main {
    /**
     * If a string exceeds a particular length, truncate it and append a
     * suffix that will hopefully allow the string to retain its uniqueness.
     * @since 1.15.5
     */
    public static String limitLength(String s, int len) {
        if (s == null || s.length() <= len)
            return s;

        String suffix = "... (truncated, #" + Math.abs(s.hashCode()) + ")";
        return s.substring(0, len - suffix.length()) + suffix;
    }
}

Related Tutorials