以下是一些 Character 类的基本用法:
创建 Character 对象:
// 使用构造方法
Character myChar1 = new Character('A');
// 使用静态方法
char myCharValue = 'B';
Character myChar2 = Character.valueOf(myCharValue);
获取 char 值:
char charValue = myChar1.charValue();
System.out.println("Character Value: " + charValue);
判断字符的类型:
char myChar = '5';
if (Character.isDigit(myChar)) {
System.out.println(myChar + " is a digit.");
} else if (Character.isLetter(myChar)) {
System.out.println(myChar + " is a letter.");
} else if (Character.isWhitespace(myChar)) {
System.out.println(myChar + " is a whitespace character.");
} else {
System.out.println(myChar + " is a symbol.");
}
字符大小写转换:
char uppercaseChar = Character.toUpperCase(myChar);
char lowercaseChar = Character.toLowerCase(myChar);
System.out.println("Uppercase: " + uppercaseChar);
System.out.println("Lowercase: " + lowercaseChar);
比较字符:
char char1 = 'A';
char char2 = 'B';
int compareResult = Character.compare(char1, char2);
if (compareResult < 0) {
System.out.println(char1 + " comes before " + char2);
} else if (compareResult > 0) {
System.out.println(char1 + " comes after " + char2);
} else {
System.out.println(char1 + " is equal to " + char2);
}
需要注意的是,Character 类是不可变的,一旦创建就不能修改。这意味着任何对 Character 对象的修改都会创建一个新的对象。
转载请注明出处:http://www.zyzy.cn/article/detail/413/Java