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'
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西