在Java中,charAt()
是一個字符串(String)對象的方法,用于返回指定索引處的字符。以下是關于charAt()
方法的一些基本信息和用法:
方法簽名:public char charAt(int index)
charAt()
方法接受一個整數參數index
,表示要獲取的字符在字符串中的位置。char
,表示返回的字符。索引范圍:
0
到string.length() - 1
。0
或大于等于string.length()
。在這種情況下,方法會拋出StringIndexOutOfBoundsException
異常。用法示例:
public class CharAtExample {
public static void main(String[] args) {
String str = "Hello, World!";
// 獲取索引為0的字符(字符串的第一個字符)
char firstChar = str.charAt(0);
System.out.println("First character: " + firstChar); // 輸出:H
// 獲取索引為4的字符(字符串的第五個字符)
char fifthChar = str.charAt(4);
System.out.println("Fifth character: " + fifthChar); // 輸出:o
// 獲取索引為-1的字符(越界,將拋出異常)
try {
char invalidChar = str.charAt(-1);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Error: Invalid index."); // 輸出:Error: Invalid index.
}
}
}
注意:在Java中,字符串的索引是從0
開始的。所以,第一個字符的索引是0
,第二個字符的索引是1
,依此類推。