Java 中charAt()的详细使用方法
1.定义
- Java 中String 类的 charAt() 方法返回给定索引号处的 char 值。 索引号从 0 开始到 n-1,其中 n 是字符串的长度。
- 如果给定的索引号大于或等于此字符串长度或负数,则返回 StringIndexOutOfBoundsException。
public char charAt(int index)
2. 代码
public class Test2 {
public static void main(String args[]){
String str = "Welcome";
int strLength = str.length();
System.out.println("Character at 0 index is: "+ str.charAt(0));
System.out.println("Character at last index is: "+ str.charAt(strLength-1));
}
}
Character at 0 index is: W
Character at last index is: e
如果果给定的索引号大于或等于此字符串长度或负数,则返回 StringIndexOutOfBoundsException。
public class Test2 {
public static void main(String args[]){
String str = "Welcome";
int strLength = str.length();
System.out.println("Character at over index is: "+ str.charAt(7));//java.lang.StringIndexOutOfBoundsException
}
}
还没有评论,来说两句吧...