java.lang.String.charAt() 方法返回指定索引处的char值。索引范围是从0到length() - 1。对于数组索引,序列的第一个char值是在索引为0,索引1,依此类推。
以下是声明java.lang.String.charAt()方法
public char charAt(int index)
参数
index -- 这是该指数的char值.
返回值
此方法返回这个字符串的指定索引处的char值。第一个char值的索引为0.
异常
IndexOutOfBoundsException -- 如果index参数为负或不小于该字符串的长度.
实例
下面的示例演示使用的java.lang.String.charAt()方法.
package com.yiibai;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "This is yiibai";
// prints character at 1st location
System.out.println(str.charAt(0));
// prints character at 5th location i.e white-space character
System.out.println(str.charAt(4));
// prints character at 18th location
System.out.println(str.charAt(17));
}
}
编译和运行上面的程序,这将产生以下结果。它也会打印空白字符。
s是一个字符穿,比如是"abc" ,其实字符串是数组实现的也可以看成是'a' ,'b' ,'c' 在你s.charAt(0)的时候相当于获取的是数据的第0个元素, 虽然你获取的是s.charAt(0)但是返回的一样是一个字符串“a” 属于报这个错误
获取字符串s中第0个字符 并把它转成char返回
char其实也是数值。将字符强制转为int,再case。
就是获取字符串中的第一个字符