Java String Escape escapeUnicodeString(final String input, final boolean escapeAscii)

Here you can find the source of escapeUnicodeString(final String input, final boolean escapeAscii)

Description

Escapes the unicode in the given string.

License

Apache License

Parameter

Parameter Description
input The input string.
escapeAscii Whether to escape ASCII or not.

Return

The escaped string.

Declaration

public static String escapeUnicodeString(final String input,
        final boolean escapeAscii) 

Method Source Code

//package com.java2s;
/*//ww  w.j av  a2s  .  co  m
 * Copyright 2012 Last.fm
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.util.Arrays;

public class Main {
    /**
     * Escapes the unicode in the given string.
     * 
     * @param input The input string.
     * @param escapeAscii Whether to escape ASCII or not.
     * @return The escaped string.
     */
    public static String escapeUnicodeString(final String input,
            final boolean escapeAscii) {
        StringBuilder returnValue = new StringBuilder("");
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (!escapeAscii && ch >= 0x0020 && ch <= 0x007e) {
                returnValue.append(ch);
            } else {
                returnValue.append("\\u");

                String hex = Integer.toHexString(input.charAt(i) & 0xFFFF);
                // If the hex string is less than 4 characters long, fill it up with leading zeroes
                char[] zeroes = new char[4 - hex.length()];
                Arrays.fill(zeroes, '0');

                returnValue.append(zeroes);
                returnValue.append(hex.toUpperCase());
            }
        }
        return returnValue.toString();
    }
}

Related

  1. escapeReservedWord(String input)
  2. escapeSelected(String str, String chars)
  3. escapeSolr(String value)
  4. escapeToFileName(String name)
  5. escapeUnicode(String s)
  6. escapeUnsafeCharacters(String anyURI, boolean escapePercent)
  7. escapeWiki(String s)
  8. escapeXML(String message)
  9. escapeXml(String str)