Java 中charAt()的详细使用方法

悠悠 2023-09-23 21:38 164阅读 0赞

1.定义

  • Java 中String 类的 charAt() 方法返回给定索引号处的 char 值。 索引号从 0 开始到 n-1,其中 n 是字符串的长度。
  • 如果给定的索引号大于或等于此字符串长度或负数,则返回 StringIndexOutOfBoundsException。

public char charAt(int index)

2. 代码

  1. public class Test2 {
  2. public static void main(String args[]){
  3. String str = "Welcome";
  4. int strLength = str.length();
  5. System.out.println("Character at 0 index is: "+ str.charAt(0));
  6. System.out.println("Character at last index is: "+ str.charAt(strLength-1));
  7. }
  8. }
  9. Character at 0 index is: W
  10. Character at last index is: e

如果果给定的索引号大于或等于此字符串长度或负数,则返回 StringIndexOutOfBoundsException。

  1. public class Test2 {
  2. public static void main(String args[]){
  3. String str = "Welcome";
  4. int strLength = str.length();
  5. System.out.println("Character at over index is: "+ str.charAt(7));//java.lang.StringIndexOutOfBoundsException
  6. }
  7. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,164人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java charAt() 方法

    用到charAt方法,了解一下 它属于Java String类 功能是用于返回指定索引处的字符。索引范围为从 0 到 字符串长度length() - 1。 语法: