charAt()
方法charAt()方法是Java中的String类方法,用于从给定字符串的指定索引中获取字符。
语法:
char String.charAt(index);
它接受索引并从String的指定位置返回字符。
注意:如果索引超出范围,则该方法将返回“字符串索引超出范围”异常。
示例
Input: str = "includeHelp" Function call: str.charAt(0) Output: "i"
码:
public class Main { public static void main(String[] args) { String str = "includeHelp"; System.out.println("character at 0 index: " + str.charAt(0)); System.out.println("character at 1 index: " + str.charAt(1)); System.out.println("character at 2 index: " + str.charAt(2)); System.out.println("character at 3 index: " + str.charAt(3)); System.out.println("character at 4 index: " + str.charAt(4)); System.out.println("character at 5 index: " + str.charAt(5)); System.out.println("character at 6 index: " + str.charAt(6)); System.out.println("character at 7 index: " + str.charAt(7)); System.out.println("character at 8 index: " + str.charAt(8)); System.out.println("character at 9 index: " + str.charAt(9)); System.out.println("character at 10 index: " + str.charAt(10)); } }
输出结果
character at 0 index: i character at 1 index: n character at 2 index: c character at 3 index: l character at 4 index: u character at 5 index: d character at 6 index: e character at 7 index: H character at 8 index: e character at 9 index: l character at 10 index: p