Java String Shorten shortenText(int maxWidth, String textValue)

Here you can find the source of shortenText(int maxWidth, String textValue)

Description

Shorten the given text t so that its length doesn't exceed the given width.

License

Open Source License

Parameter

Parameter Description
maxWidth the maximum length for the text
textValue the text to be shortened

Return

the shortened text

Declaration

public static String shortenText(int maxWidth, String textValue) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2000, 2012 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.c o  m*/
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Shorten the given text <code>t</code> so that its length
     * doesn't exceed the given width. This implementation
     * replaces characters in the center of the original string with an
     * ellipsis ("...").
     * @param maxWidth the maximum length for the text
     * @param textValue the text to be shortened
     * @return the shortened text
     */
    public static String shortenText(int maxWidth, String textValue) {
        int length = textValue.length();
        if (length < maxWidth)
            return textValue;
        String ellipsis = "..."; //$NON-NLS-1$
        int subStrLen = (maxWidth - ellipsis.length()) / 2;
        int addtl = (maxWidth - ellipsis.length()) % 2;

        StringBuffer sb = new StringBuffer();
        sb.append(textValue.substring(0, subStrLen));
        sb.append(ellipsis);
        sb.append(textValue.substring(length - subStrLen - addtl));
        return sb.toString();
    }
}

Related

  1. shortenStringForDisplay(String str, int desiredLen)
  2. shortenStringIfNecessary(String string, int maxLength, String suffixToAppend)
  3. shortenStringsByRemovingVowelsToFit(String s1, String s2, int maximumStringLength)
  4. shortenTagString(String longTag)
  5. shortenText(final String text, final int maxLength, final boolean addDots)
  6. shortenText(String originalText, int maxlength)
  7. shortenText(String string, int threshold)
  8. shortenTo(final String value, final int maxLength)
  9. shortenTo(String string, int lenght)