一、基本用法介绍
charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。
语法:public char charAt(int index)
参数:index -- 字符的索引。
返回值:返回指定索引处的字符。
实例
public class Test {
public static void main(String args[]) {
String s = "www.runoob.com";
char result = s.charAt(8);
System.out.println(result);
}
}
以上程序执行结果为:
o
二、实际应用:将一个字符串的首字母大写
private static String upperCase(String s) {
char capital = s.charAt(0);//获取首字母
String upperCase = new String(String.valueOf(capital)).toUpperCase();//首字母大写
return upperCase + s.substring(1);//截取掉s从首字母起长度为beginIndex的字符串,将剩余字符串赋值给s;
}