Java如何在指定位置获取字符串的char值?
chartAt()String类的方法返回char指定索引处的值。索引范围从0到length()-1。如果我们指定的索引超出此范围,StringIndexOutOfBoundsException则将引发异常。
这些方法使用从零开始的索引,这意味着char序列的第一个值在索引0处,下一个在索引1处,依此类推,与数组索引一样。
package org.nhooo.example.lang;
public class CharAtExample {
public static void main(String[] args) {
String[] colors = {"black", "white", "brown", "green", "yellow", "blue"};
for (String color : colors) {
//在索引号3处获取字符串的char值。因为
//索引从零开始,我们将得到第四个字符
//数组中每种颜色的颜色。
char value = color.charAt(3);
System.out.printf("The fourth char of %s is '%s'.%n", color, value);
}
}
}这是程序输出:
The fourth char of black is 'c' The fourth char of white is 't' The fourth char of brown is 'w' The fourth char of green is 'e' The fourth char of yellow is 'l' The fourth char of blue is 'e'
热门推荐
7 天仙配简短祝福语
10 立冬祝福语简短给女孩
11 牛年祝福语简短走心
12 爷爷生日会祝福语简短
13 升学宴同学祝福语简短
14 中考祝福语 简短 签状
15 留学生祝福语简短
16 闺蜜小孩祝福语简短
17 生日祝福语 简短独特情话
18 给孩子祝福语简短创意