将unicode撇号分配给char

将unicode撇号分配给char

本文介绍了Java - 将unicode撇号分配给char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将aphostrophe的值分配给char:

I want to assign the value of aphostrophe to a char:

char a = '\'';

但是我想使用untropode版本的撇号(\ u0027)来保持一致我的代码:

However I would like to use the unicode version of apostrophe (\u0027) to keep it consistent with my code:

char a = '\u0027';

但这样做会产生错误,说未关闭的字符文字。

But doing it this way gives an error saying "unclosed character literal".

如果在代码中仍然使用unicode代码,我该怎么做呢?

How can I do this assignment while still having the unicode code in the code?

推荐答案

\\\' 不起作用的原因是编译器非常早地处理unicode转义,当然,它最终成为  —它终止了文字。编译器实际上看到了这一点:

The reason \u0027 doesn't work is that the unicode escape is handled very early by the compiler, and of course, it ends up being ' — which terminates the literal. The compiler actually sees this:

char a = ''';

......这自然是个问题。 JLS在关于换行的内容中讨论了这一点,如(字符文字)。

...which naturally is a problem. The JLS talks about this in relation to line feeds and such in §3.10.4 (Character Literals).

坦率地说,我认为你是最好的写作

Frankly, I think you're best off writing

char a = '\'';

...但 char 是一个数字类型,所以你可以这样做:

...but char is a numeric type, so you could do this:

char a = 0x0027;

当然,你可以这样做:

char a = "\u0027".charAt(0);

...但我认为我们都同意这有点矫枉过正。 ; - )

...but I think we can all agree that's a bit overkill. ;-)

哦,或查看: char a ='\ u005c \ u0027'; \ u005c 当然是反斜杠  —所以编译器看到'\'')。

Oooh, or check out Greg's answer: char a = '\u005c\u0027'; (\u005c is, of course, a backslash — so the compiler sees '\'').

这篇关于Java - 将unicode撇号分配给char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:28