在Java中,String.charAt() 方法返回给定字符串中指定索引参数位置的字符。请注意,String类将其内容存储在char数组中。charAt() 方法使用提供的索引从此后台char数组中获取字符。
charAt() API 在验证特定格式的用户输入时非常有用。
1.String.charAt() API
charAt() 方法只接受一个int类型的参数,表示底层char数组中的数组索引位置。参数索引必须满足以下条件:
- 等于或大于0(零)
- 小于字符串的长度,即
String.length()
任何无效的索引参数都会导致StringIndexOutOfBoundsException。

程序员导航
优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站
2. String.charAt() 示例
在以下示例中,我们将演示在多种情况下使用charAt()方法的用法。
2.1 charAt()获取第一个字符
让我们从获取字符串的第一个字符开始,即索引位置0处的字符。
String str = "www.panziye.com";
char firstChar = str.charAt(0);
System.out.println("第一个字符是:" + firstChar);
这段代码将输出:第一个字符是:w
2.2 charAt()获取最后一个字符
String str = "www.panziye.com";
int lastIndex = str.length() - 1;
char lastChar = str.charAt(lastIndex);
System.out.println("最后一个字符是:" + lastChar);
这段代码将输出:最后一个字符是:m

AI 工具导航
优网导航旗下AI工具导航,精选全球千款优质 AI 工具集
2.3 charAt()获取任意位置字符
同样,我们可以使用有效的索引来获取字符串中的任何位置的字符。
String str = "www.panziye.com";
int index = 5; // 你想要获取的索引位置
char charAtIndex = str.charAt(index);
System.out.println("位于索引 " + index + " 处的字符是:" + charAtIndex);
只需将 index 更改为你想要获取的索引位置,即可获取相应位置的字符。
2.4 charAt()角标越界异常
再次提醒,任何无效的索引参数都会导致 StringIndexOutOfBoundsException 错误。
String str = "www.panziye.com";
int invalidIndex = 100; // 一个无效的索引位置
try {
char charAtIndex = str.charAt(invalidIndex);
System.out.println("位于索引 " + invalidIndex + " 处的字符是:" + charAtIndex);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("发生了 StringIndexOutOfBoundsException 错误:索引超出字符串范围。");
}
在尝试获取无效索引位置的字符时,会捕获到 StringIndexOutOfBoundsException 错误。
在这个Java教程中,我们学习了String类的charAt()方法,并附有示例。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



