Here you can find the source of HTMLEncode(String string)
public static String HTMLEncode(String string)
//package com.java2s; //License from project: Apache License public class Main { /**// w ww . jav a2 s.c om * Encode a string to be displayed in HTML * <p/> * If fullHTML encode, then all unicode characters above 7 bits are converted into * HTML entitites */ public static String HTMLEncode(String string) { return HTMLEncode(string, false); } public static String HTMLEncode(String string, boolean fullHTML) { if (string == null) return null; if (string.length() == 0) return 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 , if you do that you loss // word breaking if (lastWasBlankChar) { lastWasBlankChar = false; //sb.append(" "); } else { lastWasBlankChar = true; sb.append(' '); } } else { lastWasBlankChar = false; // // HTML Special Chars if (c == '"') sb.append("""); else if (c == '\'') sb.append("'"); else if (c == '&') { boolean skip = false; // we don't want to recode an existing hmlt entity if (string.length() > i + 3) { char c2 = string.charAt(i + 1); char c3 = string.charAt(i + 2); char c4 = string.charAt(i + 3); if (c2 == 'a') { if (c3 == 'm') { if (c4 == 'p') { if (string.length() > i + 4) { char c5 = string.charAt(i + 4); if (c5 == ';') { skip = true; } } } } } else if (c2 == 'q') { if (c3 == 'u') { if (c4 == 'o') { if (string.length() > i + 5) { char c5 = string.charAt(i + 4); char c6 = string.charAt(i + 5); if (c5 == 't') { if (c6 == ';') { skip = true; } } } } } } else if (c2 == 'l' || c2 == 'g') { if (c3 == 't') { if (c4 == ';') { skip = true; } } } } if (!skip) { sb.append("&"); } else { sb.append("&"); } } else if (c == '<') sb.append("<"); else if (c == '>') sb.append(">"); /*else if (c == '\n') { // warning: this can be too much html! sb.append("<br/>"); }*/ else { int ci = 0xffff & c; if (ci < 160) { // nothing special only 7 Bit sb.append(c); } else { if (fullHTML) { // Not 7 Bit use the unicode system sb.append("&#"); sb.append(new Integer(ci).toString()); sb.append(';'); } else sb.append(c); } } } } return sb.toString(); } }