Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**
     * Replace special characters with XML escapes.
     * <pre>
     * &amp; (ampersand) is replaced by &amp;amp;
     * &lt; (less than) is replaced by &amp;lt;
     * &gt; (greater than) is replaced by &amp;gt;
     * &quot; (double quote) is replaced by &amp;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("&amp;");
                break;
            case '<':
                sb.append("&lt;");
                break;
            case '>':
                sb.append("&gt;");
                break;
            case '"':
                sb.append("&quot;");
                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("&amp;");
                break;
            case '<':
                sb.append("&lt;");
                break;
            case '>':
                sb.append("&gt;");
                break;
            case '"':
                sb.append("&quot;");
                break;
            default:
                sb.append(c);
            }
        }
    }
}