1. 方法签名
codePointAt()
方法接收一个 int
类型参数,返回指定索引处的码点(code point)。码点是 Unicode 标准中为字符分配的十进制数值。
✅ 核心特点:
- 直接操作字符串底层 Unicode 编码
- 支持基本多文种平面(BMP)和辅助字符(代理对)
- 返回值范围为
0
到0x10FFFF
public int codePointAt(int index)
⚠️ 注意:索引必须在字符串范围内,否则抛出异常
2. 示例用法
通过具体示例快速掌握方法行为:
@Test
public void whenCallCodePointAt_thenDecimalUnicodeReturned() {
// 英文字符 'a' 的 Unicode 码点
assertEquals(97, "abcd".codePointAt(0));
// 代理对字符测试(如 Emoji)
String surrogatePair = "𝄞"; // 音乐符号 G clef
assertEquals(0x1D11E, surrogatePair.codePointAt(0));
}
✅ 关键验证点:
- 普通字符返回标准 Unicode 码点
- 代理对(surrogate pair)返回完整码点而非单个 char 值
- 索引从 0 开始计数
3. 异常处理
当传入非法索引时,方法会明确抛出 StringIndexOutOfBoundsException
:
@Test(expected = StringIndexOutOfBoundsException.class)
public void whenPassNonExistingIndex_thenStringIndexOutOfBoundsExceptionThrown() {
// 字符串 "abcd" 长度为 4,最大索引为 3
int a = "abcd".codePointAt(4); // 触发异常
}
❌ 常见踩坑场景:
- 索引等于字符串长度(
str.length()
) - 负索引(如
-1
) - 遍历时误用
i <= str.length()
(应使用<
)
✅ 安全实践建议:
String str = "example";
int index = 2;
if (index >= 0 && index < str.length()) {
int codePoint = str.codePointAt(index);
} else {
// 处理越界情况
}