阅读量:2
charAt() 是 Java 中的一个字符串方法,用于返回指定索引处的字符。下面是一个实际案例,展示了如何使用 charAt() 方法:
public class CharAtExample {
public static void main(String[] args) {
String str = "Hello, World!";
// 使用 charAt() 获取索引为 0 的字符
char firstChar = str.charAt(0);
System.out.println("第一个字符是: " + firstChar); // 输出: H
// 使用 charAt() 获取索引为 7 的字符
char eighthChar = str.charAt(7);
System.out.println("第八个字符是: " + eighthChar); // 输出: W
// 使用 charAt() 获取索引为 -1 的字符(会抛出 StringIndexOutOfBoundsException)
try {
char lastChar = str.charAt(-1);
System.out.println("最后一个字符是: " + lastChar);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("字符串索引越界");
}
}
}
在这个例子中,我们创建了一个名为 str 的字符串变量,包含文本 “Hello, World!”。然后,我们使用 charAt() 方法分别获取索引为 0、7 和 -1 的字符,并将它们打印出来。注意,当我们尝试获取索引为 -1 的字符时,程序会抛出一个 StringIndexOutOfBoundsException 异常,因为字符串的索引是从 0 开始的,所以最后一个字符的索引是 13,而不是 -1。
以上就是关于“java charat的实际案例”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm