Unicode-teken maken op basis van zijn nummer

Ik wil een Unicode-teken in Java weergeven. Als ik dit doe, werkt het prima:

String symbol = "\u2202";

symbool is gelijk aan “∂”. Dat is wat ik wil.

Het probleem is dat ik het Unicode-nummer ken en daaruit het Unicode-symbool moet maken. Ik probeerde (voor mij) het voor de hand liggende:

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

In dit geval is het symbool echter gelijk aan “\u2202”. Dat is niet wat ik wil.

Hoe kan ik het symbool construeren als ik het Unicode-nummer weet (maar alleen tijdens runtime — ik kan het niet hard coderen zoals in het eerste voorbeeld)?


Antwoord 1, autoriteit 100%

Je hoeft alleen je intnaar een charte casten. Je kunt dat converteren naar een Stringmet Character.toString():

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

BEWERKEN:

Onthoud dat de escape-reeksen in de Java-broncode (de \u-bits) in HEX zijn, dus als u een escape-reeks probeert te reproduceren, hebt u iets nodig als int c = 0x2202.


Antwoord 2, autoriteit 98%

Als u een UTF-16-gecodeerde code-eenheid als een charwilt krijgen, kunt u het gehele getal ontleden en ernaar casten zoals anderen hebben voorgesteld.

Als je alle codepunten wilt ondersteunen, gebruik dan Character.toChars(int). Dit behandelt gevallen waarin codepunten niet in een enkele char-waarde passen.

Doc zegt:

Converteert het opgegeven teken (Unicode-codepunt) naar de UTF-16-representatie die is opgeslagen in een char-array. Als het opgegeven codepunt een BMP-waarde (Basic Multilingual Plane of Plane 0) is, heeft de resulterende char-array dezelfde waarde als codePoint. Als het opgegeven codepunt een aanvullend codepunt is, heeft de resulterende char-array het corresponderende surrogaatpaar.


Antwoord 3, autoriteit 32%

De andere antwoorden hier ondersteunen alleen unicode tot U+FFFF (de antwoorden die betrekking hebben op slechts één instantie van char) of vertellen niet hoe je bij het eigenlijke symbool komt (de antwoorden stoppen bij Character.toChars() of daarna de verkeerde methode gebruiken), dus voeg mijn antwoord hier ook toe.

Om ook aanvullende codepunten te ondersteunen, moet dit worden gedaan:

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

Ik heb ook snel getest welke conversiemethoden werken en welke niet

int codePoint = 128149;
char[] charPair = Character.toChars(codePoint);
System.out.println(new String(charPair, 0, 2).codePointAt(0)); // 128149, worked
System.out.println(charPair.toString().codePointAt(0));        // 91, didn't work
System.out.println(new String(charPair).codePointAt(0));       // 128149, worked
System.out.println(String.valueOf(codePoint).codePointAt(0));  // 49, didn't work
System.out.println(new String(new int[] {codePoint}, 0, 1).codePointAt(0));
                                                               // 128149, worked

Opmerking: zoals @Axel in de opmerkingen vermeldde, is er met java 11 Character.toString(int codePoint)die waarschijnlijk het meest geschikt is voor de taak.


Antwoord 4, autoriteit 10%

Deze werkte prima voor mij.

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

Nu heeft text2 ∂.


Antwoord 5, autoriteit 8%

Onthoud dat chareen integraal type is en dus een geheel getal kan krijgen, evenals een char-constante.

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

Antwoord 6, autoriteit 5%

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'.

Antwoord 7, autoriteit 3%

Zo doe je het:

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

Deze oplossing is door Arne Vajhøj .


Antwoord 8, Autoriteit 3%

Hoewel dit een oude vraag is, is er een zeer eenvoudige manier om dit te doen in Java 11 die vandaag werd uitgebracht: je kunt een nieuwe overbelasting van karakter.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

Aangezien deze methode een Unicode-codepunt ondersteunt, is de lengte van de geretourneerde string niet noodzakelijkerwijs 1.

De code die nodig is voor het gegeven voorbeeld in de vraag is eenvoudigweg:

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

Deze aanpak biedt verschillende voordelen:

  • Het werkt voor elk Unicode-codepunt in plaats van alleen degenen die kunnen worden afgehandeld met behulp van een char.
  • Het is beknopt en het is gemakkelijk te begrijpen wat de code doet.
  • Het retourneert de waarde als een tekenreeks in plaats van een char[], wat vaak is wat je wilt. Het antwoord van McDowellis geschikt als u wilt dat het codepunt wordt geretourneerd als char[].

Antwoord 9

De onderstaande code schrijft de 4 unicode-tekens (weergegeven door decimalen) voor het woord “be” in het Japans. Ja, het werkwoord “zijn” in het Japans heeft 4 tekens!
De waarde van karakters is in decimalen en is ingelezen in een array van String[] — met bijvoorbeeld split. Als je Octal of Hex hebt, parseIntneem ook een radix.

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

Antwoord 10

Hier is een blok om unicode-tekens af te drukken tussen \u00c0en \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();
}

Antwoord 11

Helaas leidt het verwijderen van één speling zoals vermeld in de eerste opmerking (newbiedoodle) niet tot een goed resultaat. De meeste (zo niet alle) IDE geeft een syntaxisfout. De reden hiervoor is dat het Java Escaped Unicode-formaat syntaxis “\uXXXX” verwacht, waarbij XXXX 4 hexadecimale cijfers zijn, die verplicht zijn. Pogingen om deze string uit stukken te vouwen, mislukken. Natuurlijk is “\u” niet hetzelfde als “\\u”. De eerste syntaxis betekent ontsnapte ‘u’, de tweede betekent ontsnapte speling (wat speling is) gevolgd door ‘u’. Het is vreemd dat op de Apache-pagina’s een hulpprogramma wordt gepresenteerd dat precies dit gedrag doet. Maar in werkelijkheid is het Escape mimic utility. Apache heeft zijn eigen hulpprogramma’s (ik heb ze niet getest), die dit voor je doen. Misschien, het is nog steeds niet dat, wat je wilt hebben. Apache Escape Unicode-hulpprogramma’sMaar dit hulpprogramma 1heeft een goede benadering van de oplossing. Met hierboven beschreven combinatie (MeraNaamJoker). Mijn oplossing is om deze Escaped-mimic-string te maken en deze vervolgens terug te converteren naar unicode (om echte Escaped Unicode-beperking te voorkomen). Ik heb het gebruikt voor het kopiëren van tekst, dus het is mogelijk dat het in de uencode-methode beter is om ‘\\u’ te gebruiken, behalve ‘\\\\u’. Probeer het.

 /**
   * 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;
  }

Antwoord 12

char c = (char) 0x2202;
String s = “” + c;


Antwoord 13

(Antwoord is in Dot Net 4.5 en in Java, moet er een vergelijkbare aanpak zijn)

Ik kom uit West-Bengalen in India.
Zoals ik begrijp, is je probleem …
U wilt vergelijkbaar zijn met ‘অ’ (het is een brief in de taal van Bengaalse)
die Unicode Hex heeft: 0X0985.

Nu, als u deze waarde kent met betrekking tot uw taal, hoe kunt u dat taalspecifiek Unicode-symboolrecht produceren?

In Dot Net is het zo eenvoudig als dit:

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

Nu x is uw antwoord.
Maar dit is HEX door HEX Convert en Zin tot Verzamelingsconversie is een werk voor onderzoekers: P

Other episodes