Java String Truncate truncateString(String text, int truncateAt)

Here you can find the source of truncateString(String text, int truncateAt)

Description

Truncates a string.

License

Apache License

Parameter

Parameter Description
text the text value
truncateAt the number of characters at which the string should be truncated. Strings will never be truncated to less than 13 characters.

Declaration

static public String truncateString(String text, int truncateAt) 

Method Source Code

//package com.java2s;
/*/*  www.j a  va  2s  . com*/
 *  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 {
    static private final String _ELLIPSIS = "...";
    static private final int _ELLIPSIS_LENGTH = _ELLIPSIS.length();
    static private final int _TRUNCATE_AT_MINIMUM = 13;

    /**
     * Truncates a string.
     * @param text the text value
     * @param truncateAt the number of characters at which the
     *   string should be truncated.  Strings will never be truncated
     *   to less than 13 characters.
     */
    static public String truncateString(String text, int truncateAt) {
        if (text == null)
            return null;

        if (truncateAt < _TRUNCATE_AT_MINIMUM)
            truncateAt = _TRUNCATE_AT_MINIMUM;

        if (text.length() > truncateAt) {
            text = text.substring(0, truncateAt - _ELLIPSIS_LENGTH) + _ELLIPSIS;
        }

        return text;
    }
}

Related

  1. truncateString(String str, int length, String suffix)
  2. truncateString(String str, int maxlen)
  3. truncateString(String str, int size)
  4. truncateString(String str, int toLen)
  5. truncateString(String string, int maxLength)
  6. truncateStringAt(String source, int len)
  7. truncateStringChars(String strIn, String substituteChars, int maxChars, boolean keepRightSide)
  8. truncateStringToUtf8(final String original, final int maxBytes)
  9. truncateSubjectText(String subject)