简体   繁体   English

Java中的字符文字?

[英]Character literal in Java?

So I just started reading "Java In A Nutshell", and on Chapter One it states that: 所以我刚刚开始阅读“Java In A Nutshell”,并在第一章中指出:

"To include a character literal in a Java program, simply place it between single quotes" ie “要在Java程序中包含字符文字,只需将其放在单引号之间”即

char c = 'A'; 

What exactly does this do^? 这到底是做什么的? I thought char only took in values 0 - 65,535. 我认为char只接受0到65,535的值。 I don't understand how you can assign 'A' to it? 我不明白你怎么能给它分配'A'?

You can also assign 'B' to an int? 您还可以将'B'分配给int?

int a = 'B'

The output for 'a' is 66. Where/why would you use the above^ operation? 'a'的输出是66.你在哪里/为什么要使用上面的^操作?

I apologise if this is a stupid question. 如果这是一个愚蠢的问题,我道歉。

My whole life has been a lie. 我的一生都是谎言。

char is actually an integer type. char实际上是一个整数类型。 It stores the 16-bit Unicode integer value of the character in question. 它存储相关字符的16位Unicode整数值。

You can look at something like http://asciitable.com to see the different values for different characters. 您可以查看http://asciitable.com之类的内容,以查看不同字符的不同值。

If you look at an ASCII chart, the character "A" has a value of 41 hex or 65 decimal. 如果查看ASCII图表,字符“A”的值为41十六进制或65十进制。 Using the ' character to bracket a single character makes it a character literal. 使用'字符括起单个字符使其成为字符文字。 Using the double-quote ( " ) would make it a String literal. 使用双引号( " )将使它成为字符串文字。

Assigning char someChar = 'A'; 分配char someChar = 'A'; is exactly the same as saying char someChar = 65; char someChar = 65;完全相同char someChar = 65; .

As to why, consider if you simply want to see if a String contains a decimal number (and you don't have a convenient function to do this). 至于为什么,考虑一下你是否只想查看一个String是否包含十进制数(并且你没有方便的函数来执行此操作)。 You could use something like: 你可以使用类似的东西:

bool isDecimal = true;
for (int i = 0; i < decString.length(); i++) {
    char theChar = decString.charAt(i);
    if (theChar < '0' || theChar > '9') {
        isDecimal = false;
        break;
    }
}

In Java char literals represent UTF-16 (character encoding schema) code units. 在Java中,char文字表示UTF-16(字符编码模式)代码单元。 What you got from UTF-16 is mapping between integer values (and the way they are saved in memory) with corresponding character (graphical representation of unit code). 你从UTF-16得到的是整数值(以及它们在内存中保存的方式)与相应字符(单位代码的图形表示)之间的映射。

You can enclose characters in single quotes - this way you don't need to remember UTF-16 values for characters you use. 您可以用单引号括起字符 - 这样您就不需要记住您使用的字符的UTF-16值。 You can still get the integer value from character type and put if for example in int type (but generally not in short, they both use 16 bits but short values are from -32768 to 32767 and char values are from 0 to 65535 or so). 您仍然可以从字符类型中获取整数值,并将其置于例如int类型中(但通常不是简而言之,它们都使用16位,但短值是-32768到32767,char值是0到65535左右) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM