1. 方法签名

charAt() 方法用于返回字符串中指定索引位置的字符。索引值必须在 0String.length() - 1 的范围内。

方法定义

public char charAt(int index)

2. 使用示例

通过索引获取字符的典型用法如下:

@Test
public void whenCallCharAt_thenCorrect() {
    assertEquals('P', "Paul".charAt(0));
}

关键点

  • 索引从 0 开始计数
  • 返回值是 char 基本类型
  • 常用于遍历字符串或提取特定位置字符

3. 异常处理

当传入非法索引时,会抛出 IndexOutOfBoundsException

@Test(expected = IndexOutOfBoundsException.class)
public void whenCharAtOnNonExistingIndex_thenIndexOutOfBoundsExceptionThrown() {
    int character = "Paul".charAt(4); // 字符串长度为4,最大索引为3
}

⚠️ 常见踩坑场景

  • 索引为负数(如 charAt(-1)
  • 索引等于或大于字符串长度(如 "abc".charAt(3)
  • 空字符串调用 charAt(0)(直接抛异常)

4. 最佳实践

  1. 边界检查

    String str = "example";
    if (index >= 0 && index < str.length()) {
        char c = str.charAt(index);
    }
    
  2. 遍历替代方案

    • 使用 toCharArray() 转为数组后遍历(适合多次随机访问)
    • 使用增强 for 循环(适合顺序遍历)
  3. 性能提示

    • 单次访问时间复杂度 O(1)
    • 避免在循环中重复调用 length()(应先缓存长度值)

💡 开发技巧:当需要检查字符串首尾字符时,直接用 charAt(0)charAt(length-1)substring() 更高效


原始标题:Java String.charAt() | Baeldung