Java String Shorten shorten(String in)

Here you can find the source of shorten(String in)

Description

shorten given string (typically, a filename) by replacing the characters in the middle of the string with dots.

License

Open Source License

Parameter

Parameter Description
in string to shorten

Return

shortened string

Declaration

public static String shorten(String in) 

Method Source Code

//package com.java2s;
/*//from  w  ww.j av  a 2s.  c o m
 * Copyright (C) 2008-2011 by Simon Hefti. All rights reserved.
 * Licensed under the EPL 1.0 (Eclipse Public License).
 * (see http://www.eclipse.org/legal/epl-v10.html)
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
 * 
 * Initial Developer: Simon Hefti
 */

public class Main {
    /**
     * shorten given string (typically, a filename) by replacing the characters in
     * the middle of the string with dots.
     * 
     * @param in string to shorten
     * @return shortened string
     */
    public static String shorten(String in) {
        return shorten(in, 32, "...");
    }

    /**
     * shorten given string (typically, a filename) by replacing the characters in
     * the middle of the string with dots.
     * 
     * @param in string to shorten
     * @param maxLen string shorter than this length are not changed
     * @param replacement replacement string to use
     * @return shortened string
     */
    public static String shorten(final String in, final int maxLen, final String replacement) {
        StringBuffer sb = new StringBuffer(256);
        if (in == null) {
            return "";
        }
        if (in.length() < maxLen) {
            return in;
        }
        int half = maxLen / 2;
        int rep = replacement.length();
        if (rep > half) {
            throw new IllegalArgumentException("replacement must be shorter than half of maxLen");
        }
        int pos = half - (int) Math.ceil(rep / 2.0d);

        sb.append(in.substring(0, pos));
        sb.append(replacement);
        sb.append(in.substring(in.length() - pos));

        return sb.toString();

    }
}

Related

  1. shorten(byte[] array, int length)
  2. shorten(String className)
  3. shorten(String className)
  4. shorten(String clazz)
  5. shorten(String fullClassName)
  6. shorten(String input)
  7. shorten(String input, int length, boolean wholeWord)
  8. shorten(String label, int maxLength)
  9. shorten(String line)