Java 中的 Character 类是 java.lang 包中的一个类,用于表示 Unicode 字符。它提供了许多方法和常量来处理字符。
Character 类的常量
Character 类中有许多常量,用于表示 Unicode 字符的类别和属性。以下是一些常量的列表:
Character.MIN_VALUE
: Unicode 字符的最小值。Character.MAX_VALUE
: Unicode 字符的最大值。Character.TYPE
: Unicode 字符的类型。Character.LOWERCASE_LETTER
: 小写字母。Character.UPPERCASE_LETTER
: 大写字母。Character.DIGIT
: 数字。Character.LITERAL
: 字符串字面量。Character.SPACE_SEPARATOR
: 空格分隔符。Character.LINE_SEPARATOR
: 行分隔符。Character.PARAGRAPH_SEPARATOR
: 段落分隔符。
Character 类的方法
Character 类中有许多方法,用于处理字符。以下是一些方法的列表:
charAt(int index)
: 返回指定索引的字符。codePointAt(int index)
: 返回指定索引的 Unicode 码点。codePointCount(int beginIndex, int endIndex)
: 返回从 beginIndex 到 endIndex之间的 Unicode 码点数量。indexOf(char ch)
: 返回指定字符在字符串中的索引。lastIndexOf(char ch)
: 返回指定字符在字符串中最后出现的索引。toLowerCase()
: 将字符串转换为小写。toUpperCase()
: 将字符串转换为大写。trim()
: 将字符串的前后空格去除。
Character 类的示例代码
以下是一个使用 Character 类的示例代码:
public class CharacterExample {
public static void main(String[] args) {
// 获取指定索引的字符
char c = Character.charAt("hello", 1);
System.out.println(c); // 输出:e
// 获取指定索引的 Unicode 码点
int codePoint = Character.codePointAt("hello", 1);
System.out.println(codePoint); // 输出:101
// 获取从 beginIndex 到 endIndex 之间的 Unicode 码点数量
int codePointCount = Character.codePointCount("hello", 1, 3);
System.out.println(codePointCount); // 输出:2
// 返回指定字符在字符串中的索引
int index = Character.indexOf("hello", 'e');
System.out.println(index); // 输出:1
// 返回指定字符在字符串中最后出现的索引
int lastIndex = Character.lastIndexOf("hello", 'e');
System.out.println(lastIndex); // 输出:4
// 将字符串转换为小写
String lowerCase = "Hello".toLowerCase();
System.out.println(lowerCase); // 输出:hello
// 将字符串转换为大写
String upperCase = "hello".toUpperCase();
System.out.println(upperCase); // 输出:HELLO
// 将字符串的前后空格去除
String trimmed = " hello ".trim();
System.out.println(trimmed); // 输出:hello
}
}