Here you can find the source of truncate(String s)
public static String truncate(String s)
//package com.java2s; public class Main { public static final int MAX_CONTENT_LENGTH = 255; public static final int MAX_WORD_LENGTH = 20; public static String truncate(String s) { return truncate(s, MAX_CONTENT_LENGTH); }//from ww w . j a va 2 s . c o m /** * Removes all HTML tags and then truncate the string. * @param s the string to truncate * @param maxLength the maximum length of the returned string * @return the processed string */ public static String truncate(String s, int maxLength) { String content = filterHTML(s); // then truncate, if necessary if (content == null) { return ""; } else { StringBuffer buf = new StringBuffer(); String words[] = content.split("\\s"); for (int i = 0; i < words.length; i++) { if (buf.length() + words[i].length() > maxLength) { // truncate here buf.append("..."); return buf.toString(); } else if (words[i].length() > MAX_WORD_LENGTH) { // truncate here buf.append(words[i].substring(0, MAX_WORD_LENGTH)); buf.append("..."); return buf.toString(); } else { buf.append(words[i]); if ((i + 1) < words.length) { buf.append(" "); } } } return buf.toString(); } } /** * Filters out all HTML tags. * * @param s the String to filter * @return the filtered String */ public static String filterHTML(String s) { if (s == null) { return null; } s = s.replaceAll("<", ""); s = s.replaceAll(">", ""); s = s.replaceAll(" ", ""); s = s.replaceAll("(?s)<[Ss][Cc][Rr][Ii][Pp][Tt].*?>.*?</[Ss][Cc][Rr][Ii][Pp][Tt]>", ""); s = s.replaceAll("(?s)<[Ss][Tt][Yy][Ll][Ee].*?>.*?</[Ss][Tt][Yy][Ll][Ee]>", ""); s = s.replaceAll("(?s)<!--.*?-->", ""); s = s.replaceAll("(?s)<.*?>", ""); return s; } }