3

Please note that this question is not a duplicate.

I have a String like this:

// My String
String myString = "U+1F600";
// A method to convert the String to a real character
String unicodeCharacter = convertStringToUnicode(myString);
// Then this should print: 
System.out.println(unicodeCharacter);

How can I convert this String to the unicode character ? I then want to show this in a TextView.

Community
  • 1
  • 1
Thomas Vos
  • 12,271
  • 5
  • 33
  • 71
  • 1
    Do you really want to convert the strings dynamically or do you want constant strings representing these characters? – Henry Jul 02 '16 at 18:15
  • @Henry Like in the question, I want to convert the String to the correct Unicode character. For example, `String s = “U+1F600”;` should become `String s2 = "";`. Then I want to display that emoji in a TextView. Please see edit. – Thomas Vos Jul 02 '16 at 18:18
  • 1
    First you convert the unicode codepoint to UTF-16 and encode that as a Java string literal, i.e. `String myString = "\uD83D\uDE00";`. Then you print it using a font that has the emoji. – Andreas Jul 02 '16 at 18:23

2 Answers2

7

What you are trying to do is to print the unicode when you know the code but as String... the normal way to do this is using the method

Character.toChars(int)

like:

System.out.print(Character.toChars(0x1f600));

now in you case, you have

String myString = "U+1F600";

so you can truncate the string removing the 1st 2 chars, and then parsing the rest as an integer with the method Integer.parseInt(valAsString, radix)

Example:

String myString = "U+1F600";
System.out.print(Character.toChars(Integer.parseInt(myString.substring(2), 16)));
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Try

yourTextVIew.setText(new String(Character.toChars(0x1F60B)));
Sujay
  • 3,417
  • 1
  • 23
  • 25
  • Thanks for the answer. However, as mentioned in the question, it is already a String like this: `String myString = "U+1F600";`. – Thomas Vos Jul 02 '16 at 18:25
  • Don't just show code fragment. Provide a bit of explanation too. – Andreas Jul 02 '16 at 18:25
  • 2
    @SuperThomasLab Then do `String unicodeCharacter = new String(Character.toChars(Integer.parseInt(myString.substring(2), 16)))`. – Andreas Jul 02 '16 at 18:27
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – double-beep Feb 19 '20 at 15:31