我看过很多关于charAt()
方法的比较。
然而,有几个比较我并不是很理解。
String str = "asdf";
str.charAt(0) == '-'; // What does it mean when it's equal to '-'?
char c = '3';
if (c < '9') // How are char variables compared with the `<` operator?
任何帮助都将不胜感激。
我看过很多关于charAt()
方法的比较。
然而,有几个比较我并不是很理解。
String str = "asdf";
str.charAt(0) == '-'; // What does it mean when it's equal to '-'?
char c = '3';
if (c < '9') // How are char variables compared with the `<` operator?
任何帮助都将不胜感激。
String str = "asdf";
String output = " ";
if(str.charAt(0) == '-'){
// What does it mean when it's equal to '-'?
output= "- exists in the first index of the String";
}
else {
output="- doesn't exists in the first index of the String";
}
System.out.println(output);
它检查该字符是否存在于索引0中,这是一种比较。
至于if (c < '9')
,比较了c和9的ascii值。我不知道为什么要检查c的ascii等价物是否小于'9'的ascii等价物。
如果您想获得任何字符的ascii值,则可以:
char character = 'c';
int ascii = character;
System.out.println(ascii);
str.charAt(0) == '-';
返回一个布尔值,在这种情况下为false
。
if (c < '9')
比较'3'的ASCII值和'9'的ASCII值,并再次返回布尔值。
str.charAt(0) == '-'
如果点0处的字符为“-”,则此语句返回true,否则返回false。
if (c < '9')
这将比较字符 c 的 ASCII 值与 '9' 的 ASCII 值,分别为 99 和 57。
字符是Java中的一种原始类型,这意味着它不是一个复杂对象。因此,每次您比较chars
时,都直接比较它们的值。
Java字符根据原始Unicode规范定义,为每个字符赋予16位值。当您比较像c>'3'
或str.charAt(0) == '-'
这样的内容时,Java比较的就是这些值。