Here you can find the source of abbreviateText(final String text, final int numberOfCharacters, final String appendText)
public static String abbreviateText(final String text, final int numberOfCharacters, final String appendText)
//package com.java2s; /*/* w w w . j ava2s .c o m*/ * Copyright 2014 Hippo B.V. (http://www.onehippo.com) * * 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. */ public class Main { private static final String DEFAULT_APPEND_TEXT = " ..."; /** * Abbreviate a text to _approximately_ some number of characters, trying to * find a nice word end and then appending some string (defaulting to three dots). */ public static String abbreviateText(final String text, final int numberOfCharacters, final String appendText) { int nrChars = numberOfCharacters; if (nrChars > 0 && text != null && text.length() > nrChars) { // search a nice word end, _backwards_ from nrChars int spaceIndex = text.lastIndexOf(' ', nrChars); int dotIndex = text.lastIndexOf('.', nrChars); int commaIndex = text.lastIndexOf(',', nrChars); int questionIndex = text.lastIndexOf('?', nrChars); int exclamationIndex = text.lastIndexOf('!', nrChars); // set index to last space nrChars = spaceIndex; if (dotIndex > nrChars) { nrChars = dotIndex; } if (commaIndex > nrChars) { nrChars = commaIndex; } if (questionIndex > nrChars) { nrChars = questionIndex; } if (exclamationIndex > nrChars) { nrChars = exclamationIndex; } // final check for < 0 if (nrChars < 0) { nrChars = 0; } if (appendText != null) { return text.substring(0, nrChars) + appendText; } else { return text.substring(0, nrChars) + DEFAULT_APPEND_TEXT; } } return text; } /** * Abbreviate a text to _approximately_ some number of characters, trying to * find a nice word end and then appending three dots. */ public static String abbreviateText(final String text, final int numberOfCharacters) { return abbreviateText(text, numberOfCharacters, null); } }