1. Overview
1.概述
In this short tutorial, we’ll see how to get the ASCII value of a character in Java.
在这个简短的教程中,我们将看到如何在Java中获取一个字符的ASCII值。
2. Use Casting
2.使用浇铸
To get the ASCII value of a character, we can simply cast our char as an int:
为了得到一个字符的ASCII值,我们可以简单地将我们的char投成int。
char c = 'a';
System.out.println((int) c);
And here is the output:
这里是输出结果。
97
Remember that char in Java can be a Unicode character. So our character must be an ASCII character to be able to get its correct ASCII numeric value.
请记住,Java中的char可以是一个Unicode字符。所以我们的字符必须是ASCII字符,以便能够得到其正确的ASCII数值。
3. Character Inside a String
3.字符串内的字符
If our char is in a String, we can use the charAt() method to retrieve it:
如果我们的字符在字符串中,我们可以使用charAt()方法来检索它。
String str = "abc";
char c = str.charAt(0);
System.out.println((int) c);
4. Conclusion
4.总结
In summary, we’ve learned how to get the ASCII value of a character in Java.
综上所述,我们已经学会了如何在Java中获取一个字符的ASCII值。