Here you can find the source of truncAtWord(String a_text, int a_length)
Parameter | Description |
---|---|
a_text | the text to be truncated |
a_length | the maximum number of characters to remain in the string. |
public static String truncAtWord(String a_text, int a_length)
//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; } }