Java tutorial
//package com.java2s; //License from project: Apache License public class Main { /** * Replace special characters with XML escapes. * <pre> * & (ampersand) is replaced by &amp; * < (less than) is replaced by &lt; * > (greater than) is replaced by &gt; * " (double quote) is replaced by &quot; * </pre> * * @param string The string to be escaped. * @return The escaped string. */ public static CharSequence escape(CharSequence string) { StringBuilder sb = new StringBuilder(); escape(sb, string); return sb; } public static CharSequence escape(char[] chars, int start, int len) { StringBuilder sb = new StringBuilder(); escape(sb, chars, start, len); return sb; } public static void escape(StringBuilder sb, String string) { escape(sb, string.toCharArray(), 0, string.length()); } public static void escape(StringBuilder sb, CharSequence string) { for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&"); break; case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '"': sb.append("""); break; default: sb.append(c); } } } public static void escape(StringBuilder sb, char[] chars, int start, int len) { for (int i = start; i < len; i++) { char c = chars[i]; switch (c) { case '&': sb.append("&"); break; case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '"': sb.append("""); break; default: sb.append(c); } } } }