![](/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.