在Java中,charAt() 方法用于獲取指定索引處的字符。其語法如下:
char charAt(int index)
其中,index 表示要獲取的字符的索引,索引從0開始。例如,對(duì)于字符串 “Hello”,則:
示例代碼如下:
String str = "Hello";
char firstChar = str.charAt(0); // 獲取第一個(gè)字符
System.out.println(firstChar); // 輸出 'H'
char lastChar = str.charAt(str.length() - 1); // 獲取最后一個(gè)字符
System.out.println(lastChar); // 輸出 'o'
需要注意的是,如果指定的索引超出了字符串的長度范圍,charAt() 方法將會(huì)拋出 StringIndexOutOfBoundsException 異常。因此,在使用 charAt() 方法時(shí)應(yīng)注意索引的有效范圍。