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'
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志