Java HTML Encode textToHtml(String s)

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

Description

wrap contents as an html document

License

Apache License

Declaration

public static String textToHtml(String s) 

Method Source Code

//package com.java2s;
/**/*w ww .  ja  v  a  2s  .c o m*/
 * Razvan's public code. Copyright 2008 based on Apache license (share alike) see LICENSE.txt for
 * details.
 */

public class Main {
    /** wrap contents as an html document */
    public static String textToHtml(String s) {
        return stringToHTMLString(s);
    }

    private static String stringToHTMLString(String string) {
        StringBuffer sb = new StringBuffer(string.length());
        // true if last char was blank
        boolean lastWasBlankChar = false;
        int len = string.length();
        char c;

        for (int i = 0; i < len; i++) {
            c = string.charAt(i);
            if (c == ' ') {
                // blank gets extra work,
                // this solves the problem you get if you replace all
                // blanks with &nbsp;, if you do that you loss 
                // word breaking
                if (lastWasBlankChar) {
                    lastWasBlankChar = false;
                    sb.append("&nbsp;");
                } else {
                    lastWasBlankChar = true;
                    sb.append(' ');
                }
            } else {
                lastWasBlankChar = false;
                //
                // HTML Special Chars
                if (c == '"')
                    sb.append("&quot;");
                else if (c == '&')
                    sb.append("&amp;");
                else if (c == '<')
                    sb.append("&lt;");
                else if (c == '>')
                    sb.append("&gt;");
                else if (c == '\n')
                    // Handle Newline
                    //                    sb.append("&lt;br/&gt;");
                    sb.append("<br/>");
                else if (c == '\t')
                    sb.append("&nbsp;&nbsp;&nbsp;");
                else {
                    int ci = 0xffff & c;
                    if (ci < 160)
                        // nothing special only 7 Bit
                        sb.append(c);
                    else {
                        // Not 7 Bit use the unicode system
                        sb.append("&#");
                        sb.append(new Integer(ci).toString());
                        sb.append(';');
                    }
                }
            }
        }
        return sb.toString();
    }
}

Related

  1. htmlspecialchars(String s)
  2. htmlspecialchars(String str)
  3. textToHtml(final String s)
  4. textToHtml(String html)
  5. textToHTML(String message)
  6. textToHTML(String text)
  7. textToHtml(String text)
  8. textToHtml(String text)
  9. textToHTML(String text)