Java Unicode Escape unicodeEscapeEncode(String unicode)

Here you can find the source of unicodeEscapeEncode(String unicode)

Description

Performs escape encoding on the given string so that it can be represented using 1-byte characters.

License

Open Source License

Declaration

public static String unicodeEscapeEncode(String unicode) 

Method Source Code

//package com.java2s;
/**//from w  w w  .j a va  2  s .  co m
 * Copyright (c) 2002-2009 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   IBM - Initial API and implementation
 */

public class Main {
    /**
     * Performs escape encoding on the given string so that it can be represented using 1-byte characters.
     * Any characters higher than 0xFF are replaced with an escape of the form \\uXXXX, where XXXX is the
     * four-digit hex representation of the Unicode code point.
     */
    public static String unicodeEscapeEncode(String unicode) {
        StringBuilder result = new StringBuilder(unicode.length());
        for (int i = 0, size = unicode.length(); i < size; ++i) {
            char character = unicode.charAt(i);
            if (character > '\u00ff') {
                result.append("\\u");
                String hex = Integer.toString(character, 16);
                for (int j = hex.length(); j < 4; ++j) {
                    result.append("0");
                }
                result.append(hex);
            } else {
                result.append(character);
            }
        }

        return result.toString();
    }
}

Related

  1. unicodeEscaped(char ch)
  2. unicodeEscaped(Character ch)
  3. unicodeEscaped(Character ch)
  4. unicodeEscaped(final Character ch)
  5. unicodeEscaped(final String str)
  6. unicodeHexEscapeJava(char ch)
  7. unicodeUnescape(String st)