Java String Truncate truncate(String original, String ellipsis, int maxLength)

Here you can find the source of truncate(String original, String ellipsis, int maxLength)

Description

Truncates a String , and if necessary adds an ellipsis to the end of the string.

License

Open Source License

Parameter

Parameter Description
original a parameter
ellipsis The string to use as an ellipsis, or null to use the default (...).
maxLength If the length of the original String is greater than this value, an ellipsis will be added.

Exception

Parameter Description
StringIndexOutOfBoundsException If the length of the ellipsis is greaterthan maxLength

Return

A that is guaranteed to be no longer than maxLength .

Declaration

public static String truncate(String original, String ellipsis, int maxLength) 

Method Source Code

//package com.java2s;
/*  Copyright (C) 2009 Mobile Sorcery AB
    //from w w w.  j a v  a  2  s  .  c  om
This program is free software; you can redistribute it and/or modify it
under the terms of the Eclipse Public License v1.0.
    
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the Eclipse Public License v1.0 for
more details.
    
You should have received a copy of the Eclipse Public License v1.0 along
with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html
*/

public class Main {
    /**
     * Truncates a {@link String}, and if necessary adds an ellipsis to
     * the end of the string.
     * @param original
     * @param ellipsis The string to use as an ellipsis, or {@code null} to use the default (...).
     * @param maxLength If the length of the {@code original} {@link String} is greater than
     * this value, an ellipsis will be added.
     * @return A {@link String} that is guaranteed to be no longer than {@code maxLength}.
     * @throws StringIndexOutOfBoundsException If the length of the ellipsis is greater
     * than {@code maxLength}
     */
    public static String truncate(String original, String ellipsis, int maxLength) {
        if (original.length() > maxLength) {
            if (ellipsis == null) {
                ellipsis = "...";
            }
            return original.substring(0, maxLength - ellipsis.length()) + ellipsis;
        }
        return original;
    }
}

Related

  1. truncate(String input, int size)
  2. truncate(String message)
  3. truncate(String message, int length, boolean includeCount)
  4. truncate(String message, String substring)
  5. truncate(String original, int number)
  6. truncate(String originalString, int size)
  7. truncate(String s)
  8. truncate(String s)
  9. truncate(String s, int begin, int end)