printing characters using only ascii characters. Non-ascii characters as their hexadecimal integer value, and prefixed with "\u". - Java java.lang

Java examples for java.lang:char

Description

printing characters using only ascii characters. Non-ascii characters as their hexadecimal integer value, and prefixed with "\u".

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        char c = 'a';
        System.out.println(getEscapedString(c));
    }/*from  w ww . j a v  a2  s.c  om*/

    /**
     * Utility function for printing characters using only ascii characters.
     * Non-ascii characters as their hexadecimal integer value, and prefixed
     * with "\u". For example the greek lower-case alpha character is integer
     * value 03b1, and so the string "\u03B1" is returned.
     */
    public static String getEscapedString(char c) {
        if ((int) c >= 33 && (int) c <= 126) {
            return Character.toString(c);
        } else {
            String result = Integer.toString((int) c, 16);
            while (result.length() < 4) {
                result = "0" + result;
            }
            return "\\u" + result;
        }
    }
}

Related Tutorials