tipos codificaciones codificacion caracteres java string unicode character

java - codificaciones - Crear un caracter Unicode a partir de su numero



tipos de codificaciones (12)

Quiero mostrar un carácter Unicode en Java. Si hago esto, funciona bien:

String symbol = "/u2202";

el símbolo es igual a "∂". Eso es lo que quiero.

El problema es que conozco el número Unicode y necesito crear el símbolo Unicode a partir de eso. Intenté (para mí) lo obvio:

int c = 2202; String symbol = "//u" + c;

Sin embargo, en este caso, el símbolo es igual a "/ u2202". Eso no es lo que quiero.

¿Cómo puedo construir el símbolo si conozco su número Unicode (pero solo en tiempo de ejecución --- no puedo codificarlo como en el primer ejemplo)?


(LA RESPUESTA ESTÁ EN DOT NET 4.5 y en java, debe existir un enfoque similar)

Soy de Bengala Occidental en INDIA. Según tengo entendido, su problema es ... Desea producir un producto similar a ''অ'' (es una letra en idioma bengalí) que tiene Unicode HEX: 0X0985 .

Ahora bien, si conoce este valor con respecto a su idioma, ¿cómo va a producir ese símbolo Unicode específico del idioma correcto?

En Dot Net es tan simple como esto:

int c = 0X0985; string x = Char.ConvertFromUtf32(c);

Ahora x es tu respuesta. Pero esto es HEX mediante conversión HEX y la conversión de frase a oración es un trabajo para los investigadores: P


Aquí hay un bloque para imprimir caracteres unicode entre /u00c0 a /u00ff :

char[] ca = {''/u00c0''}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 16; j++) { String sc = new String(ca); System.out.print(sc + " "); ca[0]++; } System.out.println(); }


Así es como lo haces:

int cc = 0x2202; char ccc = (char) Integer.parseInt(String.valueOf(cc), 16); final String text = String.valueOf(ccc);

Esta solución es por Arne Vajhøj.


Desafortunadamente, eliminar una reacción como se menciona en el primer comentario (newbiedoodle) no conduce a un buen resultado. La mayoría (si no todos) IDE emite un error de sintaxis. El motivo es que el formato Java Unpedido Escapado espera la sintaxis "/ uXXXX", donde XXXX son 4 dígitos hexadecimales, que son obligatorios. Los intentos de doblar esta secuencia de piezas falla. Por supuesto, "/ u" no es lo mismo que "// u". La primera sintaxis significa ''u'', el segundo significa escape (que es reacción) seguido de ''u''. Es extraño que en las páginas de Apache se presente la utilidad, que hace exactamente este comportamiento. Pero en realidad, es la utilidad de imitación de escape . Apache tiene algunas utilidades propias (no las comprobé), que hacen este trabajo por usted. Puede ser, todavía no es eso, lo que quieres tener. Apache Escape Unicode utilities Pero esta utilidad 1 tiene un buen enfoque para la solución. Con la combinación descrita anteriormente (MeraNaamJoker). Mi solución es crear esta cadena mímica escapada y luego convertirla de nuevo a Unicode (para evitar la restricción Unicode Escaped real). Lo usé para copiar texto, así que es posible que en el método uencode sea mejor usar ''// u'' excepto ''////'. Intentalo.

/** * Converts character to the mimic unicode format i.e. ''//u0020''. * * This format is the Java source code format. * * CharUtils.unicodeEscaped('' '') = "//u0020" * CharUtils.unicodeEscaped(''A'') = "//u0041" * * @param ch the character to convert * @return is in the mimic of escaped unicode string, */ public static String unicodeEscaped(char ch) { String returnStr; //String uniTemplate = "/u0000"; final static String charEsc = "//u"; if (ch < 0x10) { returnStr = "000" + Integer.toHexString(ch); } else if (ch < 0x100) { returnStr = "00" + Integer.toHexString(ch); } else if (ch < 0x1000) { returnStr = "0" + Integer.toHexString(ch); } else returnStr = "" + Integer.toHexString(ch); return charEsc + returnStr; } /** * Converts the string from UTF8 to mimic unicode format i.e. ''//u0020''. * notice: i cannot use real unicode format, because this is immediately translated * to the character in time of compiling and editor (i.e. netbeans) checking it * instead reaal unicode format i.e. ''/u0020'' i using mimic unicode format ''//u0020'' * as a string, but it doesn''t gives the same results, of course * * This format is the Java source code format. * * CharUtils.unicodeEscaped('' '') = "//u0020" * CharUtils.unicodeEscaped(''A'') = "//u0041" * * @param String - nationalString in the UTF8 string to convert * @return is the string in JAVA unicode mimic escaped */ public String encodeStr(String nationalString) throws UnsupportedEncodingException { String convertedString = ""; for (int i = 0; i < nationalString.length(); i++) { Character chs = nationalString.charAt(i); convertedString += unicodeEscaped(chs); } return convertedString; } /** * Converts the string from mimic unicode format i.e. ''//u0020'' back to UTF8. * * This format is the Java source code format. * * CharUtils.unicodeEscaped('' '') = "//u0020" * CharUtils.unicodeEscaped(''A'') = "//u0041" * * @param String - nationalString in the JAVA unicode mimic escaped * @return is the string in UTF8 string */ public String uencodeStr(String escapedString) throws UnsupportedEncodingException { String convertedString = ""; String[] arrStr = escapedString.split("////u"); String str, istr; for (int i = 1; i < arrStr.length; i++) { str = arrStr[i]; if (!str.isEmpty()) { Integer iI = Integer.parseInt(str, 16); char[] chaCha = Character.toChars(iI); convertedString += String.valueOf(chaCha); } } return convertedString; }


El siguiente código escribirá los 4 caracteres unicode (representados por decimales) para la palabra "ser" en japonés. ¡Sí, el verbo "ser" en japonés tiene 4 caracteres! El valor de los caracteres está en decimal y se ha leído en una matriz de String [] - utilizando split por ejemplo. Si tiene Octal o Hex, parseInt tome una raíz también.

// pseudo code // 1. init the String[] containing the 4 unicodes in decima :: intsInStrs // 2. allocate the proper number of character pairs :: c2s // 3. Using Integer.parseInt (... with radix or not) get the right int value // 4. place it in the correct location of in the array of character pairs // 5. convert c2s[] to String // 6. print String[] intsInStrs = {"12354", "12426", "12414", "12377"}; // 1. char [] c2s = new char [intsInStrs.length * 2]; // 2. two chars per unicode int ii = 0; for (String intString : intsInStrs) { // 3. NB ii*2 because the 16 bit value of Unicode is written in 2 chars Character.toChars(Integer.parseInt(intsInStrs[ii]), c2s, ii * 2 ); // 3 + 4 ++ii; // advance to the next char } String symbols = new String(c2s); // 5. System.out.println("/nLooooonger code point: " + symbols); // 6. // I tested it in Eclipse and Java 7 and it works. Enjoy


Este funcionó bien para mí.

String cc2 = "2202"; String text2 = String.valueOf(Character.toChars(Integer.parseInt(cc2, 16)));

Ahora text2 tendrá ∂.


Las otras respuestas aquí solo admiten Unicode hasta U + FFFF (las respuestas tratan solo con una instancia de char) o no dicen cómo llegar al símbolo real (las respuestas se detienen en Character.toChars () o usan un método incorrecto después de eso), así que agrego mi respuesta aquí también.

Para admitir puntos de código suplementarios también, esto es lo que se debe hacer:

// this character: // http://www.isthisthingon.org/unicode/index.php?page=1F&subpage=4&glyph=1F495 // using code points here, not U+n notation // for equivalence with U+n, below would be 0xnnnn int codePoint = 128149; // converting to char[] pair char[] charPair = Character.toChars(codePoint); // and to String, containing the character we want String symbol = new String(charPair); // we now have str with the desired character as the first item // confirm that we indeed have character with code point 128149 System.out.println("First code point: " + symbol.codePointAt(0));

También hice una prueba rápida de qué métodos de conversión funcionan y cuáles no

int codePoint = 128149; char[] charPair = Character.toChars(codePoint); String str = new String(charPair, 0, 2); System.out.println("First code point: " + str.codePointAt(0)); // 128149, worked String str2 = charPair.toString(); System.out.println("Second code point: " + str2.codePointAt(0)); // 91, didn''t work String str3 = new String(charPair); System.out.println("Third code point: " + str3.codePointAt(0)); // 128149, worked String str4 = String.valueOf(code); System.out.println("Fourth code point: " + str4.codePointAt(0)); // 49, didn''t work String str5 = new String(new int[] {codePoint}, 0, 1); System.out.println("Fifth code point: " + str5.codePointAt(0)); // 128149, worked


Recuerde que char es un tipo integral y, por lo tanto, puede recibir un valor entero, así como una constante char.

char c = 0x2202;//aka 8706 in decimal. /u codepoints are in hex. String s = String.valueOf(c);


Si desea obtener una unidad de código codificada en UTF-16 como un char , puede analizar el entero y transmitirlo como otros han sugerido.

Si desea admitir todos los puntos de código, use Character.toChars(int) . Esto manejará casos donde los puntos de código no pueden caber en un solo valor de char .

Doc dice:

Convierte el carácter especificado (punto de código Unicode) en su representación UTF-16 almacenada en una matriz char. Si el punto de código especificado es un valor BMP (Basic Multilingual Plane o Plane 0), la matriz de caracteres resultante tiene el mismo valor que codePoint. Si el punto de código especificado es un punto de código suplementario, la matriz de caracteres resultante tiene el par sustituto correspondiente.


Simplemente lanza tu int a un char . Puede convertir eso a una String usando Character.toString() :

String s = Character.toString((char)c);

EDITAR:

Solo recuerda que las secuencias de escape en el código fuente de Java (los /u bits) están en HEX, así que si estás tratando de reproducir una secuencia de escape, necesitarás algo como int c = 0x2202 .


char c = (char) 0x2202; Cadena s = "" + c;


String st="2202"; int cp=Integer.parseInt(st,16);// it convert st into hex number. char c[]=Character.toChars(cp); System.out.println(c);// its display the character corresponding to ''/u2202''.