convert html letters (> and <) to < > - Java XML

Java examples for XML:XML String Escape

Description

convert html letters (> and <) to < >

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        System.out.println(htmlEsc(str));
    }//from  ww  w . j a  v a2s.  co m

    /**
     * convert html letters (&gt; and &lt;) to < > 
     * @param String str, a string to convert
     * @return String , a converted string
     */
    public static String htmlEsc(String str) {

        // test if str contains chars that has to be escaped
        // most strings do not need escape at all, and
        // for such strings this check eliminates
        // creating new string object
        StringBuffer ret = new StringBuffer();
        String tmp = "";
        int start = 0;
        int end = 0;
        while ((end = str.indexOf("&gt;", start)) > -1) {
            ret.append(str.substring(start, end));
            ret.append('>');
            start = end + 4;
        }
        ret.append(str.substring(start));
        tmp = ret.toString();
        ret = null;
        ret = new StringBuffer();
        start = end = 0;
        while ((end = tmp.indexOf("&lt;", start)) > -1) {
            ret.append(tmp.substring(start, end));
            ret.append('<');
            start = end + 4;
        }
        ret.append(tmp.substring(start));

        return (ret.toString());
    }
}

Related Tutorials