温馨提示×

如何使用Java的charat方法获取字符

小樊
81
2024-09-09 12:32:46
栏目: 编程语言

在Java中,charAt() 是一个 String 类的方法,它返回给定索引处的 char

public class Main {
    public static void main(String[] args) {
        String example = "Hello, World!";
        
        // 获取索引为4的字符('o')
        char ch = example.charAt(4);
        
        System.out.println("Character at index 4: " + ch);
    }
}

在这个例子中,我们创建了一个名为 example 的字符串变量,并使用 charAt() 方法获取索引为4的字符。然后,我们将结果打印到控制台。请注意,字符串索引从0开始,因此索引4对应于第五个字符。

0