String.charAt(int index) 方法用于获取字符串中指定索引位置的字符,索引从0开始且必须满足 0 ≤ index < 字符串长度,否则抛出 StringIndexOutOfBoundsException 异常。

Java 中用 String.charAt(int index) 方法可以获取字符串中指定位置的字符,索引从 0 开始,必须在合法范围内(0 ≤ index ),否则会抛出 <strong>StringIndexOutOfBoundsException</strong>。
基本用法:传入有效索引
调用 charAt() 时,传入一个整数作为下标,返回对应位置的 char 类型值:
- 字符串第一个字符是
charAt(0) - 最后一个字符是
charAt(str.length() - 1) - 空字符串(
"")长度为 0,任何索引都会越界
示例:
String s = "Hello";char c1 = s.charAt(0); // 'H'
char c2 = s.charAt(4); // 'o'
安全访问:先检查索引范围
避免运行时异常,建议在调用前判断索引是否有效:
立即学习“Java免费学习笔记(深入)”;
- 检查
index >= 0 && index - 尤其在处理用户输入、循环遍历或动态计算索引时很重要
示例:
String s = "Java";int pos = 5;
if (pos >= 0 && pos System.out.println(s.charAt(pos));
} else {
System.out.println("索引超出范围");
}
常见错误:越界和负索引
以下写法都会触发 StringIndexOutOfBoundsException:
-
"abc".charAt(3)(长度为 3,最大合法索引是 2) -
"abc".charAt(-1)(负数索引非法) -
"".charAt(0)(空字符串无字符)
注意:编译器不会报错,异常只在运行时发生。
替代方案:结合其他操作使用
charAt() 常用于字符级判断或简单提取,比如:
- 判断首字符是否为大写字母:
str.charAt(0) >= 'A' && str.charAt(0) - 逐个遍历字符串:
for (int i = 0; i - 配合
StringBuilder修改某位置字符(需先转为数组或用setCharAt())
不支持直接修改原字符串(String 不可变),如需替换,应构造新字符串。


















