Java String Shorten shortenText(String string, int threshold)

Here you can find the source of shortenText(String string, int threshold)

Description

Shortens the given string to be no longer than the given threshold.

License

Open Source License

Parameter

Parameter Description
string a parameter
threshold TODO

Return

the given string shortened to be no longer than the given threshold

Declaration

public static String shortenText(String string, int threshold) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 IBM Corporation 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:/*w w w  . ja v a  2 s  . co  m*/
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Shortens the given string to be no longer than the given threshold. Any removed characters are 
     * replaced with <code>...</code>.<br><br>
     * For example: <code>shortenText("this is a string to shorten text", 8)</code> would result in the string:
     * <code>"thi...xt"</code>
     * 
     * @param string
     * @param threshold TODO
     * @return the given string shortened to be no longer than the given threshold
     */
    public static String shortenText(String string, int threshold) {
        int length = string.length();
        if (length > threshold) {
            int chomp = length - threshold + 3;
            int begin = Math.round(threshold / 2) - 1;
            return string.replaceAll(string.substring(begin, begin + chomp), "..."); //$NON-NLS-1$
        }
        return string;
    }
}

Related

  1. shortenStringsByRemovingVowelsToFit(String s1, String s2, int maximumStringLength)
  2. shortenTagString(String longTag)
  3. shortenText(final String text, final int maxLength, final boolean addDots)
  4. shortenText(int maxWidth, String textValue)
  5. shortenText(String originalText, int maxlength)
  6. shortenTo(final String value, final int maxLength)
  7. shortenTo(String string, int lenght)
  8. shortenToFirstLast(String filename)
  9. shortenType(String typeText)