Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    private static final char[] entityChars = { '<', '>', '"', '\'', '&' };
    private static final String[] entityStrings = { "&lt;", "&gt;", "&quot;", "&apos;", "&amp;" };

    /**
     * Simply converts the the five reserved XML characters (&lt;,&gt;,",\,&) into
     * their escaped counterparts.
     */
    public static final String escape(String str) {
        if (str == null)
            return null;

        StringBuffer b = new StringBuffer();
        final char[] chars = str.toCharArray();
        final int len = chars.length;
        int st;

        for (int i = 0; i < len; i++) {
            st = findChar(chars[i]);
            if (st != -1)
                b.append(entityStrings[st]);
            else
                b.append(chars[i]);
        }

        return b.toString();
    }

    private static final int findChar(char c) {
        for (int i = entityChars.length - 1; i >= 0; i--)
            if (entityChars[i] == c)
                return i;
        return -1;
    }
}