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 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短