charAt()方法
该方法可以摘取一个字符串的某一个字符,作为一个单独的字符型变量。
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String str="123456"
System.out.println(str.charAt(4));//结果是5
}
}
由结果是5可以得出,字符串最左边的1不是“第一个字符”,而是像数组的排序一样,作为“第零个字符”而存在。
而charAt(int index)中的参数也不是“第index个位置的字符”而是像数组一样,表示“脚标为index的字符”。
//菜鸟教程给出的例子有点偶然性,以为“脚标为8的字符”和“第8个位置的字符”都是o,容易误解。
另外,要获取字符串中的单独字符还可以使用“先化字符串为字符数组,再对数组进行操作”的方法,可以参考:
中的toCharArray()方法。