Java HTML Encode htmlEncode(String str)

Here you can find the source of htmlEncode(String str)

Description

Replaces the chars '>', '<', and '&' with the sequences '>', '<', and '&'.

License

Open Source License

Parameter

Parameter Description
str the source string

Return

the encoded string

Declaration

public static String htmlEncode(String str) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   w  ww .j av a  2s.  co  m
     * Replaces the chars '>', '<', and '&' with the sequences '&gt;', '&lt;', and '&amp;'.
     * @param str  the source string
     * @return the encoded string
     */
    public static String htmlEncode(String str) {
        StringBuilder result = null;
        for (int i = 0, max = str.length(), delta = 0; i < max; i++) {
            char c = str.charAt(i);
            String replacement = null;
            if (c == '&') {
                replacement = "&amp;";
            } else if (c == '<') {
                replacement = "&lt;";
            } else if (c == '>') {
                replacement = "&gt;";
            }

            if (replacement != null) {
                if (result == null) {
                    result = new StringBuilder(str);
                }
                result.replace(i + delta, i + delta + 1, replacement);
                delta += (replacement.length() - 1);
            }
        }
        if (result == null) {
            return str;
        }
        return result.toString();
    }
}

Related

  1. HtmlEncode(String str)
  2. HTMLEncode(String str)
  3. htmlEncode(String str)
  4. htmlEncode(String str)
  5. htmlEncode(String str)
  6. htmlEncode(String string)
  7. HTMLEncode(String string)
  8. htmlEncode(String string)
  9. HtmlEncode(String strInput)