Here you can find the source of shortenContent(String s, int maxLength)
public static String shortenContent(String s, int maxLength)
//package com.java2s; public class Main { /**/*from ww w . j a v a 2 s . co m*/ * Shorten the full content to create short content, which has a special * character occurs as much as maxOccurrence or has as much as masChar * characters. * * @param fullContent * the full content * @param ch * the pattern character * @param maxOccurrence * the max occurrence * @param maxChar * the max char * @return the shorten string */ public static String shortenContent(final String fullContent, final String ch, final int maxOccurrence, final int maxChar) { int occur = 0; int begin = 0; int end = fullContent.indexOf(ch); StringBuilder result; if (end == -1) { if (fullContent.length() < maxChar) { result = new StringBuilder(fullContent); } else { result = new StringBuilder(fullContent.substring(begin, maxChar - 3)); result = result.append("..."); } } else { result = new StringBuilder(); while (end != -1 && occur <= maxOccurrence && result.length() < (maxChar - 3)) { result.append(fullContent.substring(begin, end)); begin = end; end = fullContent.indexOf(ch, end + 1); occur++; } if (result.length() - 3 >= maxChar) { result.substring(0, maxChar - 3); result = result.append("..."); } else if (occur <= maxOccurrence) { result.append(fullContent.substring(begin, fullContent.length())); } else { result = result.append("..."); } } return result.toString(); } public static String shortenContent(String s, int maxLength) { if (s.length() > maxLength) { return s.substring(0, maxLength - 3) + "..."; } else { return s; } } public static String toString(Object obj) throws Exception { if (obj == null) { return ""; } else { return obj.toString(); } } }