Java String Escape escapeCharacters(String string)

Here you can find the source of escapeCharacters(String string)

Description

Substitutes all illegal characters in the given string by the value of EscapingXMLStreamWriter#substitute .

License

Apache License

Parameter

Parameter Description
string a parameter

Declaration

public static String escapeCharacters(String string) 

Method Source Code

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

import java.util.Arrays;

import java.util.List;

public class Main {
    public static final char substitute = '\uFFFD';
    private static final List<Character> LEGAL_CONTROL_CHARS = Arrays.asList('\n', '\r', '\t');

    /**/* w  ww.j  ava  2 s  .c o  m*/
     * Substitutes all illegal characters in the given string by the value of
     * {@link EscapingXMLStreamWriter#substitute}. If no illegal characters
     * were found, no copy is made and the given string is returned.
     *
     * @param string
     * @return
     */
    public static String escapeCharacters(String string) {

        char[] copy = null;
        boolean copied = false;
        for (int i = 0; i < string.length(); i++) {
            if (isIllegal(string.charAt(i))) {
                if (!copied) {
                    copy = string.toCharArray();
                    copied = true;
                }
                copy[i] = substitute;
            }
        }
        return copied ? new String(copy) : string;
    }

    private static boolean isIllegal(char c) {
        return isControlCharcter(c);
    }

    public static boolean isControlCharcter(int i) {

        return !LEGAL_CONTROL_CHARS.contains(i) && Character.isISOControl(i);
    }
}

Related

  1. escape(String s)
  2. escape(String str)
  3. escape(String string, String chars)
  4. escapeASN1(String str)
  5. escapeCellText(String text, boolean wrap, boolean multiline)
  6. escapeHTML(String s)
  7. escapeHTML(String source)
  8. escapeHTMLTags(String in)
  9. escapeInstanceIdentifier(String instanceIdentifier)