tags:

views:

104

answers:

3

Hello all, This may be a silly question but... Say I have a String like 4e59 which represents a special unicode character. How can I add the \u to the beginning of that character so that it displays correctly? I've tried the simplest solution of:

String str = "4e59";
System.out.println("\\u"+str);

And several other variants, what am I missing?

+4  A: 

You need to convert it to a char:

System.out.println((char) Integer.parseInt("4e59", 16));
Greg Hewgill
Integer.valueOf() returns an Integer object, which then needs to be converted to an int, (and then into a char), which is kind of extraneous. Integer.parseInt() returns an int directly
newacct
That's true. I've changed my answer.
Greg Hewgill
+7  A: 

The \u is parsed at compile time, not run time, so just prefixing your string with "\u" isn't going to work.

You can use Integer.parseInt to do this parsing at runtime:

System.out.println((char)Integer.parseInt("4e59", 16));
Chi
In case brandon was interested, this also works:char c = 0x4E59;
Gunslinger47
+5  A: 

Others have already answered with how to do this, but if you're interested I can explain why prepending "\u" didn't work: the "\uXXXX" sequences are converted to the corresponding unicode character at compile time by javac (by the lexer, which is the first step in compilation, in fact). In your code, the lexer sees a string containing just "\u" and so doesn't touch it.

The \uXXXX encoding will work anywhere, not just inside strings. Both of these lines are identical if you put them in a Java source file:

int i;

\u0069\u006E\u0074 \u0069\u003B
Lachlan
Holy mother of cow !!!
Amarghosh