Création D'un caractère Unicode à partir de son numéro

Je veux afficher un caractère Unicode en Java. Si je fais cela, cela fonctionne très bien:

String symbol = "u2202";

Le symbole est égal à"∂". C'est ce que je veux.

Le problème est que je connais le numéro Unicode et que je dois créer le symbole Unicode à partir de cela. J'ai essayé (pour moi) la chose évidente:

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

Cependant, dans ce cas, le symbole est égal à "u2202". Ce n'est pas ce que je veux.

Comment puis-je construire le symbole si je connais son numéro Unicode (mais seulement au moment de l'exécution---I vous ne pouvez pas le coder en dur comme le premier exemple)?

88
demandé sur Paul Reiners 2011-04-07 22:40:45

13 réponses

Il suffit de lancer votre int à un char. Vous pouvez le convertir en String en utilisant Character.toString():

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

Modifier:

Rappelez-vous simplement que les séquences d'échappement dans le code source Java (les bits \u) sont en hexadécimal, donc si vous essayez de reproduire une séquence d'échappement, vous aurez besoin de quelque chose comme int c = 0x2202.

55
répondu dty 2011-04-07 21:30:35

Si vous voulez obtenir une unité de code codée UTF-16 en tant que char, Vous pouvez analyser l'entier et le convertir comme d'autres l'ont suggéré.

Si vous voulez soutenir tous les points de code, utilisez Character.toChars(int). Cela traitera les cas où les points de code ne peuvent pas tenir dans une seule valeur char.

Doc dit:

Convertit le caractère spécifié (point de code Unicode)en sa représentation UTF-16 stockée dans un tableau char. Si le point de code spécifié est un BMP (Plan multilingue de base ou Plan 0), le tableau char résultant a la même valeur que codePoint. Si le point de code spécifié est un point de code supplémentaire, le tableau char résultant a la paire de substitution correspondante.

112
répondu McDowell 2014-11-25 02:31:17

Les autres réponses ici ne supportent que unicode JUSQU'à U + FFFF (les réponses traitant d'une seule instance de char) ou ne disent pas comment accéder au symbole réel (les réponses s'arrêtant au caractère.toChars() ou en utilisant une méthode incorrecte après cela), donc en ajoutant ma réponse ici aussi.

Pour soutenir les points de code supplémentaires aussi, c'est ce qui doit être fait:

// 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));

J'ai aussi fait un test rapide pour savoir quelles méthodes de conversion fonctionnent et lesquelles ne fonctionnent pas

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
17
répondu eis 2013-04-16 10:49:48

Rappelez-vous que char est un type intégral, et peut donc recevoir une valeur entière, ainsi qu'une constante char.

char c = 0x2202;//aka 8706 in decimal. \u codepoints are in hex.
String s = String.valueOf(c);
5
répondu ILMTitan 2011-04-07 21:22:00

Celui-ci a bien fonctionné pour moi.

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

Maintenant text2 aura ..

5
répondu MeraNaamJoker 2013-11-27 10:09:57

Voici comment vous le faites:

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

Cette solution {[5] } est de Arne Vajhøj.

2
répondu Paul Reiners 2015-05-05 14:09:28
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'.
2
répondu Kapil K. Kushwah 2017-07-24 06:06:07

Le code ci-dessous écrira les 4 caractères unicode (représentés par des décimales) pour le mot "be" en japonais. Oui, le verbe "être" en Japonais, a 4 caractères! La valeur des caractères est en décimal et elle a été lue dans un tableau de String [] - en utilisant split par exemple. Si vous avez Octal ou Hex, parseInt Prenez également une base.

// 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
1
répondu user96265 2015-06-09 21:38:36

Malheureusement, supprimer un jeu comme mentionné dans le premier commentaire (newbiedoodle) ne conduit pas à un bon résultat. La plupart (sinon tous) IDE problèmes erreur de syntaxe. La raison en est que le format Java Escaped Unicode attend la syntaxe "\ uXXXX", où XXXX sont 4 chiffres hexadécimaux, qui sont obligatoires. Les tentatives de plier cette chaîne à partir de morceaux échouent. Bien sûr, "\u" n'est pas la même chose que "\\u". La première syntaxe signifie échappé 'u', la seconde signifie échappé backlash (qui est backlash) suivi de 'u'. Il est étrange, que sur les pages Apache est présenté utilitaire, qui fait exactement ce comportement. Mais en réalité, c'est - Échapper à imiter utilitaire. Apache a ses propres utilitaires (Je ne les ai pas testés), qui font ce travail pour vous. Peut-être, il est toujours pas que, ce que vous voulez avoir. Apache Échappement Unicode utilitaires, Mais cet utilitaire 1 avoir une bonne approche de la solution. Avec la combinaison décrite ci-dessus (MeraNaamJoker). Ma solution est de créer cette chaîne Mimique échappée puis convertissez-le en unicode (pour éviter une réelle restriction Unicode échappée). Je l'ai utilisé pour copier du texte, il est donc possible, que dans la méthode uencode sera préférable d'utiliser '\\u' sauf '\\\\u'. Essayer.

  /**
   * 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;
  }
0
répondu hariprasad 2014-05-28 15:34:05

Bien que ce soit une vieille question, il existe un moyen très facile de le faire dans Java 11 qui a été publié aujourd'hui: vous pouvez utiliser une nouvelle surcharge de caractères.toString():

public static String toString​(int codePoint)

Returns a String object representing the specified character (Unicode code point). The result is a string of length 1 or 2, consisting solely of the specified codePoint.

Parameters:
codePoint - the codePoint to be converted

Returns:
the string representation of the specified codePoint

Throws:
IllegalArgumentException - if the specified codePoint is not a valid Unicode code point.

Since:
11

Comme cette méthode prend en charge n'importe quel point de code Unicode, la longueur de la chaîne renvoyée n'est pas nécessairement 1.

Le code nécessaire pour l'exemple donné dans la question est simplement:

    int codePoint = '\u2202';
    String s = Character.toString(codePoint); // <<< Requires JDK 11 !!!
    System.out.println(s); // Prints ∂

Cette approche offre plusieurs avantages:

  • cela fonctionne pour n'importe quel point de code Unicode plutôt que seulement ceux qui peuvent être manipulés en utilisant un char.
  • , C'est concis, et il est facile de comprendre ce que fait le code.
  • il renvoie la valeur sous forme de chaîne plutôt que char[], ce qui est souvent ce que vous voulez. la réponse Postée par McDowell est appropriée si vous voulez que le point de code soit retourné comme char[].
0
répondu skomisa 2018-09-26 02:18:14

Char C = (char)0x2202; Chaîne s = "" + c;

-1
répondu dave110022 2016-10-20 03:34:45

Voici un bloc pour imprimer les caractères unicode entre \u00c0 à \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();
}
-1
répondu fjiang_ca 2016-10-29 17:05:22

(la réponse est dans DOT NET 4.5 et en java, il doit y avoir une approche similaire existe)

Je suis du Bengale Occidental en Inde. Si je comprends bien votre problème est ... Vous voulez produire similaire à ' অ ' (c'est une lettre en langue Bengali) qui a Unicode HEX: 0X0985.

Maintenant, si vous connaissez cette valeur en ce qui concerne votre langue, comment allez-vous produire ce symbole Unicode spécifique à la langue ?

Dans Dot Net, c'est aussi simple que ceci:

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

Maintenant x est votre réponse. Mais ceci est HEX par conversion hexadécimale et la conversion de phrase en phrase est un travail pour les chercheurs: P

-4
répondu Suman Kr. Nath 2015-06-21 15:23:31