3

I need to print a unicode literal string as an equivalent unicode character.

System.out.println("\u00A5"); // prints  ¥

System.out.println("\\u"+"00A5"); //prints \u0045  I need to print it as ¥ 

How can evaluate this string a unicode character ?

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Pradeep
  • 97
  • 1
  • 8
  • Not sure I understand your question... The first option already prints what you want, doesn't it? – jcaron Jul 02 '14 at 23:09
  • 2
    I guess op wants to dynamically create Unicode during livetime. – PM 77-1 Jul 02 '14 at 23:10
  • What if someone wanted to just print "\u"? Are you *actually* looking for a string parser? You could always use Rhino's. – David Ehrmann Jul 02 '14 at 23:17
  • 2
    Have a look at answers to [Howto unescape a Java string literal in Java](http://stackoverflow.com/questions/3537706/howto-unescape-a-java-string-literal-in-java/4298836#4298836). – PM 77-1 Jul 02 '14 at 23:20

3 Answers3

7

As an alternative to the other options here, you could use:

int codepoint = 0x00A5; // Generate this however you want, maybe with Integer.parseInt
String s = String.valueOf(Character.toChars(codepoint));

This would have the advantage over other proposed techniques in that it would also work with Unicode codepoints outside of the basic multilingual plane.

clstrfsck
  • 14,715
  • 4
  • 44
  • 59
3

Convert it to a character.

System.out.println((char) 0x00A5);

This will of course not work for very high code points, those may require 2 "characters".

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
3

If you have a string:

System.out.println((char)(Integer.parseInt("00A5",16)));

probably works (haven't tested it)

jcaron
  • 17,302
  • 6
  • 32
  • 46
  • 1
    If you want high code point support you can use a combination of this answer (for the integer parsing) and the answer of msandiford... – Maarten Bodewes Jul 03 '14 at 13:37