Java String Truncate truncate(String s)

Here you can find the source of truncate(String s)

Description

truncate

License

Open Source License

Declaration

public static String truncate(String s) 

Method Source Code

//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("&lt;", "");
        s = s.replaceAll("&gt;", "");
        s = s.replaceAll("&nbsp;", "");
        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;
    }
}

Related

  1. truncate(String message, int length, boolean includeCount)
  2. truncate(String message, String substring)
  3. truncate(String original, int number)
  4. truncate(String original, String ellipsis, int maxLength)
  5. truncate(String originalString, int size)
  6. truncate(String s)
  7. truncate(String s, int begin, int end)
  8. truncate(String s, int i)
  9. truncate(String s, int length)