Here you can find the source of abbreviate(String str, int maxWidth)
public static String abbreviate(String str, int maxWidth)
//package com.java2s; /**/*from w ww . j a v a 2 s .c o m*/ * $Revision $ * $Date $ * * Copyright (C) 2005-2010 Jive Software. All rights reserved. * * Licensed 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 { public static String abbreviate(String str, int maxWidth) { if (null == str) return null; if (str.length() <= maxWidth) return str; else return (new StringBuilder()).append(chopAtWord(str, maxWidth)).append("...").toString(); } public static String chopAtWord(String string, int length, int minLength) { if (length < 2) throw new IllegalArgumentException((new StringBuilder()).append("Length specified (").append(length) .append(") must be > 2").toString()); if (minLength >= length) throw new IllegalArgumentException("minLength must be smaller than length"); int sLength = string != null ? string.length() : -1; if (sLength < 1) return string; if (minLength != -1 && sLength < minLength) return string; if (minLength == -1 && sLength < length) return string; char charArray[] = string.toCharArray(); if (sLength > length) { sLength = length; for (int i = 0; i < sLength - 1; i++) { if (charArray[i] == '\r' && charArray[i + 1] == '\n') return string.substring(0, i + 1); if (charArray[i] == '\n') return string.substring(0, i); } if (charArray[sLength - 1] == '\n') return string.substring(0, sLength - 1); for (int i = sLength - 1; i > 0; i--) if (charArray[i] == ' ') return string.substring(0, i).trim(); } else if (minLength != -1 && sLength > minLength) { for (int i = 0; i < minLength; i++) if (charArray[i] == ' ') return string; } if (minLength > -1 && minLength <= string.length()) return string.substring(0, minLength); else return string.substring(0, length); } public static String chopAtWord(String string, int length) { return chopAtWord(string, length, -1); } }