Java String Shorten shorten(String label, int maxLength)

Here you can find the source of shorten(String label, int maxLength)

Description

Shortens the given label to the given maximum length and filters non-printable characters.

License

Apache License

Parameter

Parameter Description
label the label
maxLength the max length

Return

the shortened label

Declaration

public static String shorten(String label, int maxLength) 

Method Source Code

//package com.java2s;
/*/*from w w  w.  java 2 s.  c  o m*/
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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 DOT_DOT_DOT = "...";

    /**
     * Shortens the given label to the given maximum length
     * and filters non-printable characters.
     * 
     * @param label the label
     * @param maxLength the max length
     * 
     * @return the shortened label
     */
    public static String shorten(String label, int maxLength) {
        if (label == null) {
            return null;
        }

        // shorten label
        if (maxLength < 3) {
            return DOT_DOT_DOT;
        }
        if (label.length() > maxLength) {
            label = label.substring(0, maxLength / 2) + DOT_DOT_DOT
                    + label.substring(label.length() - maxLength / 2, label.length());

        }

        // filter non-printable characters
        StringBuffer sb = new StringBuffer(maxLength + 3);
        for (int i = 0; i < label.length(); i++) {
            char c = label.charAt(i);
            if (Character.isISOControl(c)) {
                sb.append('.');
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }
}

Related

  1. shorten(String clazz)
  2. shorten(String fullClassName)
  3. shorten(String in)
  4. shorten(String input)
  5. shorten(String input, int length, boolean wholeWord)
  6. shorten(String line)
  7. shorten(String msg, int front, String join, int end)
  8. shorten(String name, int max)
  9. shorten(String nameForUI, int maxLen)