Java String Truncate truncAtWord(String a_text, int a_length)

Here you can find the source of truncAtWord(String a_text, int a_length)

Description

Truncate a string at a word boundary

License

Open Source License

Parameter

Parameter Description
a_text the text to be truncated
a_length the maximum number of characters to remain in the string.

Return

the truncated string

Declaration

public static String truncAtWord(String a_text, int a_length) 

Method Source Code

//package com.java2s;
/*//w w w  . ja  v  a2s .  c o  m
 * @(#) StringUtils.java Jul 20, 2005
 * Copyright 2005 Frequency Marketing, Inc. All rights reserved.
 * Frequency Marketing, Inc. PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

public class Main {
    /**
     * Truncate a string at a word boundary
     * @param a_text the text to be truncated
     * @param a_length the maximum number of characters to remain in the string.
     * @return the truncated string
     */
    public static String truncAtWord(String a_text, int a_length) {
        String text = a_text;
        if (null != a_text && text.length() > a_length) {
            /*
             * Search backwards for a word boundary a maximum of 20 characters.
             */
            int backEnd = 20;
            if (backEnd > a_length) {
                backEnd = a_length - 1;
            }

            int finalLength = a_length;
            char character;
            for (int backTrip = 1; backTrip <= backEnd && a_length - backTrip > 0; backTrip++) {
                character = text.charAt(a_length - backTrip);
                if (Character.isWhitespace(character)) {
                    finalLength = a_length - backTrip;
                    break;
                }
            }

            if (finalLength > 0) {
                text = text.substring(0, finalLength);
            }
        }
        return text;
    }
}

Related

  1. truncateValue(String value, int limit, String endChars)
  2. truncateWhenUTF8(final String s, final int maxBytes)
  3. truncateWhiteSpace(int len, int tabSize, String indentStr)
  4. truncateWithDefault(String value, int size, String defaultValue)
  5. truncateWithEllipsis(String str, int maxLength)
  6. truncString(String in, int len)
  7. truncuate(String s, int maximumLength, String append)
  8. truncVal(String s)