![](/img/trans.png)
[英]Performance comparison of charAt() method of String vs StringBuilder in Java
[英]Java String/Char charAt() Comparison
我已经看到了使用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值。 我不知道你为什么要检查ascii当量的c是否小于ascii等价'9'。
如果你想获得任何char的ascii值,那么你可以:
char character = 'c';
int ascii = character;
System.out.println(ascii);
str.charAt(0) == '-';
返回一个布尔值,在本例中为false
。
if (c < '9')
将'3'的ascii值与ascii值'9'进行比较并再次返回布尔值。
str.charAt(0) == '-'
如果第0点处的字符为“ - ”,则此语句返回true,否则返回false。
if (c < '9')
这将c的ascii值与ascii值'9'进行比较,在这种情况下分别为99和57。
字符是Java中的原始类型,这意味着它不是一个复杂的对象。 因此,每次对chars
进行比较时,都会直接比较它们的值。
Java字符是根据原始的unicode规范定义的,它为每个字符赋予16位值。 这些是Java在比较c>'3'
或str.charAt(0) == '-'
类的值时所比较的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.