Here you can find the source of abbreviate(String str, int preferredLength)
Parameter | Description |
---|---|
str | the string to abbreviate |
preferredLength | the maximum length we would like to see |
public static String abbreviate(String str, int preferredLength)
//package com.java2s; /******************************************************************************* * Copyright (c) 2010, 2012 Institute for Dutch Lexicology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License./*from w ww . ja v a 2 s .c o m*/ *******************************************************************************/ public class Main { /** * Abbreviates a string for display if necessary. * * Also replaces line breaks with spaces. Uses overshootAllowed of 0, and adds ellipsis if * abbreviated. * * @param str * the string to abbreviate * @param preferredLength * the maximum length we would like to see * @return the (possibly) abbreviated string */ public static String abbreviate(String str, int preferredLength) { return abbreviate(str, preferredLength, 0, true); } /** * Abbreviates a string for display if necessary. * * Also normalizes whitspace (replacing a line break with a space). * * @param str * the string to abbreviate * @param preferredLength * the maximum length we would like to see * @param overshootAllowed * how many more characters than the previous value is allowable * @param addEllipsis * whether or not we should add "..." at the end if we abbreviated * @return the (possibly) abbreviated string */ public static String abbreviate(String str, int preferredLength, int overshootAllowed, boolean addEllipsis) { String result = str.replaceAll("\\s+", " "); // normalize whitespace if (result.length() > preferredLength + overshootAllowed) { int i = result.substring(0, preferredLength + 1).lastIndexOf(" "); if (i >= 1) result = result.substring(0, i); else result = result.substring(0, preferredLength); if (addEllipsis) result += "..."; } return result.trim(); } }