Here you can find the source of shorten(String input, int length, boolean wholeWord)
Parameter | Description |
---|---|
input | The text to shorten. |
length | The maximum length of the resulting text, ellipsis included. |
wholeWord | Whether to take care for splitting the text at word boundaries only. |
public static String shorten(String input, int length, boolean wholeWord)
//package com.java2s; /*//w w w. ja va 2 s .co m * Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eike Stepper - initial API and implementation * Yatta Solutions - [466264] Enhance UX in simple installer */ public class Main { public static final String EMPTY = ""; public static String HORIZONTAL_ELLIPSIS = "\u2026"; /** * Shortens the given text to be as long as the given length (including the * appended ellipsis). * * @param input The text to shorten. * @param length The maximum length of the resulting text, ellipsis included. * @param wholeWord Whether to take care for splitting the text at word * boundaries only. */ public static String shorten(String input, int length, boolean wholeWord) { if (input == null) { return EMPTY; } if (length <= HORIZONTAL_ELLIPSIS.length()) { throw new IllegalArgumentException("Length must at least " + HORIZONTAL_ELLIPSIS.length() + 1); } if (input.length() <= length) { return input; } int ellipsisPos = length - HORIZONTAL_ELLIPSIS.length() - 1; if (wholeWord) { ellipsisPos = findLastSpaceBetween(input, 0, ellipsisPos); } String result = input.substring(0, ellipsisPos); result += HORIZONTAL_ELLIPSIS; return result; } private static int findLastSpaceBetween(String text, int startPosition, int endPosition) { int index = endPosition; char lastBeforeEllipsis = text.charAt(index); while (lastBeforeEllipsis != ' ') { index--; if (index <= startPosition) { index = -1; break; } lastBeforeEllipsis = text.charAt(index); } return index; } }