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'