Java String Truncate truncateAtWord(String input, int length)

Here you can find the source of truncateAtWord(String input, int length)

Description

Returns first part of string upto specified length (breaks at word, greedy)

License

Open Source License

Parameter

Parameter Description
input a parameter
length character limit

Declaration

public static String truncateAtWord(String input, int length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//  w ww .j av a  2s  . c o m
     * Returns first part of string upto specified length (breaks at word, greedy)
     *
     * @param input
     * @param length character limit
     * @return
     */
    public static String truncateAtWord(String input, int length) {
        int offset;
        offset = 2;
        if (input == null || input.length() < (length - offset)) {
            return input;
        }
        int iNextSpace;
        iNextSpace = input.lastIndexOf(" ", length);
        String trunc = input;
        try {
            trunc = String.format(input.substring(0, (iNextSpace > 0) ? iNextSpace : (length - offset)).trim());
            return trunc + " ...";
        } catch (Exception e) {
            return trunc;
        }
    }
}

Related

  1. truncateAndTrim0(String str, String delim)
  2. truncateAt(final String input, final String... substrings)
  3. truncateAt(String str, char chr)
  4. truncateAtMaxLength(String source, int maxLength, boolean addEllipsis)
  5. truncateAtWhitespace(String text, int length)
  6. truncateBodyText(String input)
  7. truncateByCharLength(String string, int maxLength)
  8. truncateByCharLengthWithEllipsis(String string, int maxLength)
  9. truncateCellValue(String x, int maxChars)