Java unicode question
This may be a silly question but... Say I have a String
like 4e59
which represents a special unicode c开发者_StackOverflowharacter. 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?
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));
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
You need to convert it to a char
:
System.out.println((char) Integer.parseInt("4e59", 16));
精彩评论