Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    public static String replaceSpecialCharacters(String value) {
        if (value == null)
            return value;
        //only replace & if it not already an escaped sequence
        char[] val = value.toCharArray();
        int pos = 0;

        while (pos < val.length) {
            if (val[pos] == '&') {
                int ampPos = pos;
                //move over until last non-whitespace character to see if ;
                while (pos < val.length && (val[pos] + "").matches("[^\\s]") && pos < ampPos + 5) {
                    pos++;
                }

                if (val[pos] != ';') {
                    pos = pos + 3;
                    String newValue = value.substring(0, ampPos) + "&amp;";
                    if (val.length > pos + 1) {
                        newValue += value.substring(ampPos + 1);
                    }
                    value = newValue;
                    val = value.toCharArray();
                }
            }
            pos++;
        }
        value = value.replace("<", "&lt;");
        value = value.replace(">", "&gt;");
        value = value.replace("\"", "&quot;");
        value = value.replace("'", "&apos;");
        return value;
    }
}