Converts a given String to a String, where non-ASCII chars a replaced by a Unicode Sequence. - Java java.lang

Java examples for java.lang:String Unicode

Description

Converts a given String to a String, where non-ASCII chars a replaced by a Unicode Sequence.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String input = "java2s.com";
        System.out.println(convertToUnicode(input));
    }/* ww w  .ja  v a  2  s  . c  om*/

    /**
     * Converts a given String to a String, where non-ASCII chars a replaced by a Unicode Sequence.
     * 
     * Quelle: http://www.daniweb.com/software-development/java/threads/147397
     * modified
     * 
     * @param input
     * @return
     * @author DanielAl
     */
    public static String convertToUnicode(String input) {
        StringBuffer ostr = new StringBuffer();

        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);

            if ((ch >= 0x0020) && (ch <= 0x007e)) { // Does the char need to be converted to unicode?
                ostr.append(ch); // No.
            } else { // Yes.
                ostr.append("\\U+"); // own unicode format
                String hex = Integer.toHexString(input.charAt(i) & 0xFFFF); // Get hex value of the char.
                for (int j = 0; j < 4 - hex.length(); j++)
                    // Prepend zeros because unicode requires 4 digits
                    ostr.append("0");
                ostr.append(hex.toLowerCase()); // standard unicode format.
                ostr.append("\\"); // own unicode format
            }
        }
        return (new String(ostr)); // Return the stringbuffer cast as a string.
    }
}

Related Tutorials