在Java中,charAt()
是一个字符串方法,用于返回指定索引处的字符。以下是如何使用charAt()
方法的示例:
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
// 使用charAt()获取索引为0的字符
char firstChar = str.charAt(0);
System.out.println("第一个字符是: " + firstChar); // 输出: H
// 使用charAt()获取索引为4的字符
char fifthChar = str.charAt(4);
System.out.println("第五个字符是: " + fifthChar); // 输出: l
// 使用charAt()获取索引为-1的字符(会抛出StringIndexOutOfBoundsException异常)
char lastChar = str.charAt(-1);
}
}
请注意,如果索引超出字符串的范围,charAt()
方法将抛出StringIndexOutOfBoundsException
异常。因此,在使用此方法时,请确保索引在字符串的有效范围内。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java charat有哪些应用